guide intro matlab

26
MAPS2001: Scientific Computing Matlab Usage Guidelines This document covers most of the Matlab programming skills that will be required for the course. It is intended for active reading (i.e. you work through the examples by entering the code in Matlab). By the end of session 4 you should be feeling confident enough to start using what you have learned to develop code for some scientific applications Contents 1. A Gentle Introduction to MATLAB ...................................................................................................................... 1 Essential reading for session 1 exercises 2. Flow Control ........................................................................................................................................................ 7 Essential reading for session 2 exercises 3. Creating Functions ............................................................................................................................................. 12 Essential reading for session 2 exercises 4. Understanding Arrays ....................................................................................................................................... 17 Essential reading for session 3 exercises 5. Function Handles ............................................................................................................................................... 24 Essential reading for session 4 exercises

Upload: tabooga

Post on 06-Nov-2015

65 views

Category:

Documents


0 download

DESCRIPTION

intro to matlabI am not the author

TRANSCRIPT

  • MAPS2001: Scientific Computing Matlab Usage Guidelines

    This document covers most of the Matlab programming skills that will be required for the course. It is intended for

    active reading (i.e. you work through the examples by entering the code in Matlab).

    By the end of session 4 you should be feeling confident enough to start using what you have learned to develop code

    for some scientific applications

    Contents

    1. A Gentle Introduction to MATLAB ...................................................................................................................... 1

    Essential reading for session 1 exercises

    2. Flow Control ........................................................................................................................................................ 7

    Essential reading for session 2 exercises

    3. Creating Functions ............................................................................................................................................. 12

    Essential reading for session 2 exercises

    4. Understanding Arrays ....................................................................................................................................... 17

    Essential reading for session 3 exercises

    5. Function Handles ............................................................................................................................................... 24

    Essential reading for session 4 exercises

  • 1. A Gentle Introduction to MATLAB The Language of Technical Computing

    AIMS : Practice entering expressions into the Command Window.

    Introduce some of the functionality of Matlab, and important computing concepts.

    Practice using the Matlab editor for creating scripts.

    Matlab is a scientific calculator! Try to work out what result the following expression will give before you enter it into the Matlab terminal window:

    >> (7+sin(pi/2))/2/2*5^2-8

    Matlab allows variable creation

    In mathematical sciences, a variable refers a quantity of interest, whose value may be subject to change. For example, if we wished to model a game involving the roll of two dice, we might say:

    Let be the value thrown on die 1 Let be the value thrown on die 2

    Here, and are variables. Note, however, that a variable does not need to refer to a single number. For example, the variable might be a vector or a matrix. In computer science, the term variable has a similar meaning. When a variable is created, its current value is stored in computer memory so that we can access it later for use in programs or calculations.

    Try the following expressions

    >>a = (7+sin(pi/2))/2/2*5^2-8;

    >>a

    >>b = 7;

    >>a=b;

    >>a

    >>a*b

    >>c = 'Hello World!'

    >>banana = [1,2,3,4];

    >>a*banana

    TIP! Variable names are case sensitive and must start with a letter. Try to use meaningful names. For example, square_matrix.

    TIP! You can press the up arrow key on your keyboard to copy expressions from previous lines.

    Matlab means MATRIX LABORATORY

    In computing terminology, matrices are called arrays, with a column vector being a ( 1) array, and a row vector being a (1 ) array.

    However, the term array is more general than the term matrix, and in Matlab everything is an array. For example, the number 1 is a (1 1) array, whilst the string hello is a (1 5) character array.

    The semi-colon is used to stop the result being

    printed on screen.

    Because variables can be overwritten, it is necessary to give unique names to each variable in your work.

    The variable c is a string, and the variable banana

    is a row vector. You will see shortly that these two

    types of variable share similar properties.

    Page 1

  • Try the following expressions

    Row vectors. Notice that we can use a comma or a space to separate the columns >>my_row=[1 2 3] >>my_row2=[1,2,3]

    Column vectors. A semi-colon is used to separate the rows >>my_column=[1;2;3]

    Matrices. The columns are separated by commas or spaces and the rows are separated by semi-colons >>my_matrix=[1 2 3 4;1 3 5 -1;2 4 6 8]

    We can define a string as a character array. The following two expressions are equivalent >> my_string=['h','e','l','l','o']

    >> my_string2='hello'

    We can find out the dimensions of the array by using size. The variable my_row is a (1 3) array, and the variable my_matrix is a (3 4) array. What about my_string2?

    >>size(my_row) >>size(my_matrix)

    >>size(my_string2)

    To obtain only the number of rows or columns we can add a second argument to size: >>size(my_matrix,1) (number of rows)

    >>size(my_matrix,2) (number of columns)

    We can find out the number of elements (items) in an array using numel: >>numel(my_matrix)

    And we can extract elements from arrays by using parentheses as follows:

    >>my_string2(2) (gives the second element from my_string2) >>my_matrix(2,1) (gives the element in the second row and first column of my_matrix)

    Elements can also be extracted from a multi-dimensional array using a single index. For example, the expression below gives the 5th element of my_matrix, reading down the columns from position (1,1). Because there are three rows, this element is in the 2nd row, 2nd column.

    >>my_matrix(5)

    You should also be aware that the indices do not need to be scalar valued. For instance, we can extract the elements from the first and third columns in the second row of the matrix, by typing

    >>my_matrix(2,[1,3])

    Getting lists of values

    It is very straightforward to get a list of equally spaced values. For example, if we want the values between 0 and 1, with step size 0.1, we can simply type

    >>my_vector = 0:0.1:1

    This type of notation can also be used for indexing elements of an array. For example, we can extract the first three elements from the second row of my_matrix by inputting

    my_matrix(2,1:3)

    Since this matrix has 4 columns, we could extract the whole second row by typing my_matrix(2,1:4). However, the same result can be more easily achieved by writing my_matrix(2,:)

    Sometimes we may want to define a location relative to the last row or the last column, and this can be done using end. For example, to refer to the last 3 items in the last row of my_matrix, we can type my_matrix(end,end-2:end)

    Page 2

  • clear and clc

    A list of currently defined variables can be found in the Workspace pane. This can help you to avoid variable

    name conflicts. If you want to remove a variable from memory, you can do so using clear. For example

    >>clear my_matrix >>clear all (remove all Workspace objects from memory)

    To empty the screen, you can type

    >>clc

    This command does not affect the variables in the workspace.

    Operations on arrays

    Some (but not all) of the inbuilt matlab functions can operate on arrays. For example, you might like to test out the

    function sin (which we have already seen) for the following input

    >>my_vector = pi/4:pi/12:pi/2; >>result_1 = sin(my_vector)

    Some other useful algebraic functions that can operate on arrays are given below

    exp(A) : array of values for . log(A) : array of values log for .

    sqrt(A) : array of values for . abs(A) : array of values || for .

    Test out the value of log(10). Some of you might be surprised! In common with many computing languages, matlab uses the natural logarithm by default. If you want the logarithm of a value x in base 10, you can type log10(x).

    Of course, you could get the logarithm in any base by typing log(x)/log(b).

    Elementwise vs matrix operations

    If you try out the expression

    >>my_vector^2

    then you will encounter an error. The reason for the error is that the exponent operator ^ performs matrix multiplication. The expression above is equivalent to typing

    >>my_vector*my_vector

    which is meaningless unless my_vector has equal numbers of rows and columns. If you want to square every

    element in an array, then you can use the element-wise operators .^ and .* instead. The element-wise division operator ./ is also defined. Try them now:

    >>my_vector.^2 >>my_vector.*my_vector

    >>my_vector./my_vector

    Can you think of a way of calculating 1/ for every in an array?

    Another matrix operation

    Test out the expressions below, to see if you can work out what action is performed by the' (apostrophe) operator.

    >>result_1*result_1'

    >>result_1'*result_1

    If you have difficulty, try a simpler example where result_1 = [1 2];

    Page 3

  • Getting help from Matlab In this short course you will only learn to use a small fraction of Matlabs functionality. There will be many times when you want to understand more about how a given function works. The Matlab help documentation is there for you!

    Type the word sin into the Matlab Command Window

    Highlight the word using either the mouse or the keyboard

    Press F1 on your keyboard

    You should now see a help window displaying information about how to use the sin function. Alternatively (for less detail) try typing

    >>help sin

    Introducing the Matlab editor

    So far, all of your calculations have been performed directly from the Matlab terminal window. This method of entering statements is useful for short calculations, or for testing expressions. However, it is not possible to go back and make changes to our statements, and writing and maintaining large projects is not convenient. If we close the terminal window and re-open it, we will have to re-enter everything. To avoid such difficulties, we will use the Matlab editor, which will also provide the means to develop our own functions later.

    Before opening the editor, navigate to a suitable location for saving your work, in the Current Folder pane.

    Next, click on New Script in the ribbon menu

    You will see a blank editor page. Notice the absence of a command prompt (>>). You can input expressions here in the

    same way as you would in the Command Window, except that when you press enter the commands will not be

    executed. This allows you to continue writing or editing. You can run the whole thing through the Command Window

    when you are ready.

    To see how this works, first copy and paste the following code into the editor window. The code is for demonstration purposes only, and at this stage, you will not be required to understand the given expressions.

    u=linspace(0,pi,50)';

    v=linspace(0,2*pi,50);

    X=cosh(u)*cos(v);

    Y=cosh(u)*sin(v);

    Z=sinh(u)*ones(size(v));

    surf(X,Y,Z);

    grid on;

    title('hyperboloid of one sheet');

    xlabel('X'); ylabel('Y'); zlabel('Z');

    Click on the green arrow in the ribbon bar, marked Run. You will be prompted to save your work first. Give your file a suitable name, such as demo1.m. The file extension .m, identifies that this is either a script file or a function. We are writing a script here.

    Keeping track of it all

    From now on, we will use the text editor for almost everything, and so you will end up with a large number of files. Make sure that you set the Current Folder to a sensible location, and try to develop a meaningful naming scheme. Some of your assignments will require you to make use of results from earlier weeks, so please ensure that you create a backup. Dont forget that the Command Window is still a useful environment for testing out ideas quickly. Think of it as a play area!

    Page 4

  • Curve plotting

    The easiest way to produce a 2d plot in matlab is by using the command plot(x,y), where x and y are vectors

    containing the coordinates to be plotted.

    For instance, to produce a plot of sin() for the range [, ], we can type

    x = -pi:0.25:pi; %vector in steps of 0.25; y = sin(x); %the sin function works on vectors as well as scalars plot(x,y)

    Try it now, in a new blank editor window. You could save your file under the name sin_curve.m. When you press Run, a plot will be generated.

    We can make our plots look more fancy. Try replacing the last line in your script file that reads plot(x,y)with: [Note that a lot of these properties can also be set by using the drop down menu options in the figure window]

    figure %opens a new figure window plot(x,y,'r--*') %the last argument specifies the plot style (red,--*) title('Plot showing sin(\theta) and cos(\theta) on same axes') xlabel('-\pi \leq \theta \leq \pi') ylabel('label the vertical axis') axis([-pi,pi,-1.1,1.1]) %choose the axis limits %gca means 'get current axis' and can be used to set axis properties set(gca,'XTick',-pi:pi/2:pi) %choose where to place tick marks set(gca,'FontName','Symbol') %this system font allows mathematical notation set(gca,'XTickLabel',{'-p','-p/2','0','p/2','p'}) %label the ticks hold on %allows us to keep plotting on the same axes plot(x,cos(x),'b--o') %plot in blue this time, with round plot markers hold off %stop plotting on the current set of axes

    Using linspace

    In the above example, vector x wasnt created very thoughtfully, because the step size 0.25 doesnt properly divide

    the interval! This is easy to fix. For example, we could choose the step size to be 2*pi/99 if we wanted 100 points,

    here. In general, however, a better solution is to use linspace(-pi,pi,100) to tell matlab that you want a vector

    of 100 equally spaced points between and (including the endpoints).

    Making sense of it all

    Consider the following program. It contains several new ideas that we have not learned about yet, and so it probably looks meaningless to you! Save the program under the name jumble.m and run it from the Command Window by typing jumble and pressing enter. If you run it a few times, you will be able to verify what the code does, but that wont help you to understand how it works

    words = {'matlab','jumble','easy','difficult','answer','xylophone'}; word = words{randi(size(words),1)}; wlen = length(word);struck = 0; while struck

  • % 'JUMBLE' A RANDOMLY SELECTED WORD

    % A version of this algorithm could be used in a game, where participants % have to guess what the unjumbled word is

    % To jumble the word, we use an algorithm called the FisherYates shuffle. % The method involves selecting characters from the list in a random order % Characters that have been selected are 'struck' (crossed out).

    % THE ALGORITHM (example illustration):

    % At each step we select an unstruck character at random and swap with the

    % last unstruck char

    % | unstruck | struck % +---+---+---+---+---+---+ % | j | u | m | b | l | e | choosing the third character... % +---+---+---+---+---+---+

    % | unstruck | struck % +---+---+---+---+---+---+ % | j | u | e | b | l | m | now the last character is struck % +---+---+---+---+---+---+ choosing the first character...

    % | unstruck | struck % +---+---+---+---+---+---+ % | l | u | e | b | j | m | now the last two characters are struck % +---+---+---+---+---+---+ continue until all chars are struck

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    words = {'matlab','jumble','easy','difficult','answer','xylophone'}; word = words{randi(size(words),1)}; %Select a random word from the list wlen = length(word); struck = 0; %The number of chars that have been struck out %The following steps are repeated until all chars are struck: while struck>a = 1+3i; b = 2-i;

    >>a*b

    >>real(a*b)

    >>imag(a*b)

    >>conj(a)

    >>angle(a)

    >>abs(a)

    Be rational!

    Get real!

    Page 6

  • 2. Flow Control Conditional statements and loops

    AIMS : Understand how conditional statements and loops can be used to implement decisions, repeat processes,

    and develop more sophisticated programmatic structures.

    (Boolean) logic

    Boolean logic deals with true/false situations. The values true and false are represented by 1 and 0, respectively, and can be combined using the operations AND (&) and OR (|). Try to complete the following table, to see what you already know about AND and OR. The correct answers are given at the end of this section.

    A B A&B A|B

    0 0

    0 1

    1 0

    1 1

    The & and | operators can operate on arrays as well as on scalars. For example,

    >>[1 0 1] & [0 0 1]

    returns [0 0 1], since 1&0 = 0, 0&0 = 0, 1&1=1.

    Negation

    ~X gives the logical negation of X, so for example ~(0|1) would give 0, since (0|1) returns 1.

    Relationships between values

    Complete the table below for the relationship between values a and b. Answers are provided at the end of this section.

    a b a=b greater or equal

    a~=b not equal

    4 5

    4 4

    5 4

    Equality

    To test if two quantities are equal, we cannot use the ordinary equality sign, because it is reserved for defining variables!

    For example

    p=4; q=5; p=q

    simply results in setting both p and q equal to 5. To test whether p and q have the same value, we use a double

    equality symbol ==

    For example, you might like to try typing

    p=4; q=5; p==q

    which gives the result 0 (false), since 4~=5. Page 7

  • Short-circuit operators

    It is often un-necessary to test all parts of a logical expression to get the result that we need. Consider the following

    possibilities:

    A or B If A is true then we do not need to test B

    A and B If A is false then we do not need to test B

    In the short-circuit operators || and && , the second expression is evaluated only when the result is not fully

    determined by the first expression.

    Logical array indexing

    The logical operators >, 5

    gives the result

    [0 0 1 1 1]

    This provides a way of selecting elements from arrays that satisfy certain conditions. For example

    V = 4:8; %define an array V = [4,5,6,7,8]

    V(V>5); %select only the elements of V that are greater than 5

    To determine whether two arrays are equal, we use

    isequal(A,B)

    which returns true if all of the elements of A are the same as the elements of B.

    Conditional operator:

    The sequence of commands in a program can be set to depend on whether certain conditions evaluate to true or false. We do this using the following code structure:

    if Condition

    Statements 1 else

    Statements 2 end

    A flow-diagram representation is shown on the

    right. Diamonds are used to illustrate

    conditions, and rectangles are used to illustrate

    statements.

    Test out the following example:

    x = input('Type in an integer : ');

    if isprime(x)

    disp('Prime number! :)')

    else

    disp('Not prime :(')

    end

    Condition

    Statements 1 Statements 2

    true false

    Page 8

  • Loop operator (while)

    Often, we want to repeat a sequence of commands many times,

    until a certain condition is met. This can be achieved by typing:

    while Condition Statements end

    A flow-chart visualisation is shown on the right. The same

    behaviour can also be accomplished in a slightly different way by

    using break as shown below. When break is encountered,

    matlab exits the current loop structure, but continues with any

    other evaluations.

    while 1 %always true Statements

    if Condition Statements break; %exit end

    end

    Test out the example code given here:

    Method 1 i = 1; %Make sure that the iteration variable is pre-set while i

  • Loop operator (for)

    A special type of loop is useful when we want to repeat a sequence of

    commands a set number of times. We could do this using while, but is

    more convenient to write

    for x=x0:step:x1

    statements end

    The pattern of behaviour can be represented using the same flow chart

    symbols that we have already seen, but it looks cumbersome. The IBM

    preparation symbol (hexagon) offers a convenient representation, and is

    illustrated in the flow chart on the right

    For a toy example of this type of loop, try:

    for i=1:10

    disp(i)

    end

    A challenge: what is the problem here, and how could you fix it?

    The example below is supposed to report the sum of elements in each row of matrix A. However, the author has made a terrible mistake. The corrected code is given at the end of this section.

    A = [1,2,3;4,5,6;7,8,9];

    m = size(A,1); %Number of rows

    n = size(A,2); %Number of columns

    for i=1:m

    row = A(i,:); %Extract row vector from A

    total = 0; %We will add up the elements in the row

    for i=1:n

    total = total+row(i);

    end;

    fprintf(1,['Sum of elements in row %.0f = ',num2str(total),'\n'],i);

    end;

    Hint: The mistake is not in this line

    ---------------------------------------------------------------------------------------

    Some basic example programs using loops will be given at the end of the next section

    ---------------------------------------------------------------------------------------

    x = x0,step,x1

    Statements

    Page 10

  • Boolean logic (solution)

    A B A&B A|B

    0 0 0 0

    0 1 0 1

    1 0 0 1

    1 1 1 1

    Did you get it right? Notice that the answer to A|B is true if either of A,B is true, or if both are true. So, the next time that someone asks you if you like red or white wine, remember that it would be perfectly logical to answer with yes or no!

    There is also an exclusive or condition (xor) that evaluates to true only if exactly one of A and B is true, but we will not encounter it in this course.

    Relationships between values (solution)

    a b a=b a~=b

    4 5 1 1 0 0 1

    4 4 0 1 0 1 0

    5 4 0 0 1 1 1

    Challenge solution

    The variable i was used for two different purposes within the same loop! [To refer to the row number, and to the column number]

    Here is the corrected code:

    A = [1,2,3;4,5,6;7,8,9];

    m = size(A,1); %Number of rows

    n = size(A,2); %Number of columns

    for i=1:m %i refers to the row number

    row = A(i,:); %Extract row vector from A

    total = 0; %We will add up the elements in the row

    for j=1:n %j refers to the column number

    total = total+row(j);

    end;

    fprintf(1,['Sum of elements in row %.0f = ',num2str(total),'\n'],i);

    end;

    Page 11

  • 3. Creating Functions

    The black box

    The term function refers to a relationship between a set of inputs and a set of outputs. You can think of a function as a black box. We often do not need to understand how it works to use it, but it is definitely an advantage if we do! You have already seen examples of built-in Matlab functions, such as the sine function sin. In this section we will learn to create our own functions.

    Turn your script file into a function

    You can turn a .m file into a function by adding the following information in the first line:

    function [out1,out2,...] = my_function(in1,in2,...)

    The list of values in1,in2,... are the input arguments

    The list of values out1,out2,... are returned by the function

    The name my_function must match the file name. For example, if you call the function prime_test, then you need to save it under the name prime_test.m, in a folder where matlab can access it (normally your Current Folder).

    You should also add a comment immediately below the function line, describing how it is to be used. We will be able to access this information from the Matlab terminal window by typing

    help my_function

    (where my_function is the name of your function)

    Example 1:

    As a simple example, we will create a function that tests a given integer to see if it is even. We do this by evaluating

    the remainder on division by 2. The in-built malab function mod(n,m) gives the modulus of n after division by m.

    When n and m are both positive, this is the same as the remainder. For example, mod(7,3) is equal to 1.

    Enter the following text into a new blank editor script and save it in your Current Folder under the name is_even.m

    function flag = is_even(x)

    % flag = is_even(x) tests to see whether the given integer x is even,

    % and returns 1 if it is, 0 if it is not.

    % The function also displays a message

    r = mod(x,2); %remainder after division by 2

    if r==0

    disp('input is even!')

    flag = 1;

    else

    disp('input is not even!')

    flag = 0;

    end;

    Now return to the Command Window and test the following expressions:

    >>is_even(37) >>is_even(-12)

    >> help is_even

    BLACK BOX Outputs Inputs

    Page 12

  • Example 2: testing primality

    We will write a function flag = prime_test(n) that determines if a given natural number n is prime. The value of flag is 1 if the number is prime, and 0 if it is not. The test can be implemented by attempting to divide n by

    numbers in the range 2:sqrt(n), using a for loop. If one of the values gives no remainder, then n is not prime!

    A flow chart illustrating the prime_test program is shown below.

    There are two ways in which the loop can exit. The natural way is when the index becomes greater than sqrt(n), which will occur if all of the numbers have been tested and no divisors have been found. In that case, n is prime. The other way that the loop can exit is if we find an exact divisor for n. Then there is no reason to continue, because we have determined that n is not prime and so we forcefully exit the loop using break. The matlab code for this program is shown below.

    function flag = prime_test(n)

    % flag = prime_test(n) tests the given natural number n to see if it is

    % prime, and returns 1 if it is, 0 otherwise

    flag = 1;

    for i = 2:1:sqrt(n)

    if mod(n,i) == 0

    flag = 0;

    break;

    end

    end

    Save this function in your current working directory, under the filename prime_test.m Then, try out the following statements in the terminal window:

    help prime_test

    prime_test(27)

    prime_test(29)

    prime_test(1)

    prime_test(-1)

    prime_test([1,2,3])

    prime_test(n)

    mod(n,i)=0

    i=2,1,sqrt(n)

    flag=1 (assume n is prime)

    flag=0 (change flag if not prime)

    flag

    false true

    Page 13

  • Bullet proofing

    The function above gives an incorrect result for n=1 (1 is not prime), and gives a meaningless result for n=-1 and when n is a vector. We should try to protect our functions from incorrect use. For example, to ensure that the input

    for n is a positive integer, we can add the following lines at the start of the program

    if ~isscalar(n) || mod(n,1)~=0 || n

  • Example 3: Find the maximum element in an array

    function max = my_max(v)

    % my_max(v) finds the maximum element in array v

    if ~isreal(v) %test to ensure that array v contains only real numbers

    error('my_max:argChk','input must be an array of real numbers!')

    end;

    n = numel(v); %number of elements in array

    % Notice that this code works with both matrices and vectors

    max = v(1); %assume that first element in array is max

    for i = 2:n

    check_val = v(i); %get next value for testing

    if check_val>max %if value is larger than max, replace max

    max=check_val;

    end;

    end;

    Test for a few different inputs. For example:

    >>my_max([1 3 3 2])

    >>my_max([sqrt(-1), 2])

    >>A = randi([0,1000],10,10); % Array of random integers from 0-1000

    >>my_max(A)

    >>my_max('aasbcuasycgikpaor') % Might give you a surprise!

    Example 4: Find the maximum element in an array

    This function uses prime_test as a subroutine. Both functions must be saved in your Current Folder

    function list_primes(n)

    % list_primes(n) prints a list of the first n primes

    % (n must be an integer)

    if ~isscalar(n) || mod(n,1)~=0 || sign(n)

  • Example 5: Calculate the vector product

    function c = my_cross(a,b)

    % c = dot(a,b) calculates the vector product of vectors a and b

    % Check that the inputs are numeric

    if ~isnumeric(a)||~isnumeric(b)

    error('my_dot:argChk','Inputs must be numeric quantities.')

    end;

    % Check that inputs are the same size

    if ~isequal(size(a),size(b))

    error('my_dot:argChk','Inputs must be the same size.')

    end;

    % Get dimensions

    [n,m] = size(a);

    % Check that inputs are 3-vectors

    if not((n==1 && m==3) || (m==1 && n==3))

    error('my_dot:argChk','Inputs must be 3-vectors')

    end;

    %------------------------------------------------------------------------

    % Get elements of vector c

    c1 = a(2)*b(3)-a(3)*b(2);

    c2 = a(3)*b(1)-a(1)*b(3);

    c3 = a(1)*b(2)-a(2)*b(1);

    %------------------------------------------------------------------------

    % ensure that vector c has the same size as a and b

    if n==1,

    c = [c1 c2 c3];

    else

    c = [c1;c2;c3];

    end;

    Some useful bullet-proofing tools:

    isnumeric : determine if input is a numeric array

    isreal : determine if all array elements are real numbers

    isscalar : determine if input is scalar

    Page 16

  • 4. Understanding Arrays AIMS :

    Learn to manipulate numeric and character arrays

    Appreciate the importance of array pre-allocation for memory management

    Introduce cell arrays

    Object class

    In object oriented programming, objects (such as variables or functions) are grouped into classes that share

    particular attributes. The classes describe sets of behaviours or methods that can be applied to the objects.

    There are 16 fundamental classes in Matlab, shown in the figure below, with each of these being further broken down

    into subclasses.

    For MAPS2001 we will only consider the following classes: logical

    char

    numeric (actually a group of classes, with similar properties) cell

    function handle (we will discuss function handles in the next section)

    Getting information about objects in the Workspace

    We can use the commands class and whos to find out information about objects in the Workspace:

    It might be helpful to clear the Workspace first, which you can do by typing clear.

    Next, we create instances of a string (a character array) and a numeric array: a = 'this is a string'; %Create an instance of the class 'char'

    b = magic(3); %Create an instance of a numeric class

    Find out the class of each of these variables by typing: class(a)

    class(b)

    Or find out details about all currently defined Workspace objects by entering: whos

    The class of our numeric array is double, which is short for double precision floating point format. Most numeric arrays in Matlab are of this type. In this course we will not look at the types of numeric array in any detail, although we will briefly discuss floating point format after reading week.

    Types of

    array

    Page 17

  • Manipulating Numeric Arrays

    We are already familiar with the basic method of entering numeric arrays. For example, A = [1 2 3;4 5 6;7 8 9];

    We also learned how to extract elements. Can you remember how to get the last two items from the first row, for example? Here, we will extend what we learned about indexing, to provide a way to edit arrays.

    For instance, we can change one of the elements of the array: A(2,2)=0 %Replace element at position (2,2) with zero

    Or change several elements at once: A(1,[1,3])=[-3,-1] %Replace elements (1,1) and (1,3) with -3 and -1

    We can even replace an entire row or column. A(1,:)=[1,1,1] %Replace first row with ones

    The row vector [1,1,1] can also be generated by typing ones(1,3);

    and so another way of replacing the first row with ones is: A(1,:)=ones(1,size(A,2)) %size(A,2) is the number of columns in A

    Similarly, we replace the last column of A with zeros here: A(:,3)= zeros(size(A,1),1) %size(A,1) is the number of rows in A

    The commands ones and zeros are incredibly useful. However, a more general way of getting a constant vector is to use repmat, which repeats the rows or columns of a matrix a specified number of times.

    For example, a column vector of three zeros can be generated by typing: repmat(0,3,1) %the numeric object 0 is an array with 1 row and 1 column

    whilst a (3 3) matrix whose columns are all the same as the first column of A is given by: repmat(A(:,1),1,3)

    Clearly, we have the ability to swap elements in an array. For instance, to swap the elements in position (2,1) and (2,3) we could introduce temporary variables a and b as follows:

    a = A(2,1); b = A(2,3); A(2,1) = b; A(2,3) = a; clear a; clear b;

    However, the same result could be achieved in matlab in a single step: A(2,[1,3])=A(2,[3,1]) %Swap elements (2,1) and (2,3)

    We can also delete or add rows or columns (although we will soon see that this is not always advisable) A(1,:)=[] %Delete first row my_row = [1 2 3];

    A = [A;my_row] %Append row to the end of matrix A A = [my_row;A] %Prepend row to the beginning of matrix A [A A A] %What does this final result give?

    Inf and NaN

    Inf refers to infinity (can also be written inf).

    NaN means Not a Number (can also be written nan).

    These are important concepts within Matlab. Try entering the following expressions into the terminal window, and check the class of Inf and NaN to confirm that they are both numeric objects.

    a=1/0

    a-a

    0*a

    Page 18

  • Some common arrays The following commands are frequently useful for generating arrays:

    zeros(n,m) ( ) array of zeros

    ones(n,m) ( ) array of ones

    nan(n,m) ( ) array of NaNs

    eye(n) ( ) identity matrix

    Compare the following two code snippets:

    % ---- Snippet 1 ----

    clear all;

    N = 10;

    list = [];

    for i=1:N

    list(i)=i;

    end;

    % ---- Snippet 2 ----

    clear all;

    N = 10;

    list = zeros(1,N);

    for i=1:N

    list(i)=i;

    end;

    Try to run each of these snippets separately. At first glance, both seem to be fine. They certainly give the same result, which is simply a vector of the first N natural numbers. However, if you are working in the matlab editor, you may notice that the first code snippet gives you a warning message, that says something like : List might be growing in a loop. Consider pre-allocating for speed

    Dont ignore the warnings!

    Try changing the value of N to 10^5, and then run each snippet again.

    Snippet 1 appears to take much longer. If you want to know how long, you can use tic and toc like this:

    % ---- Snippet 1 ----

    clear all;

    N = 10^7;

    tic;

    list = [];

    for i=1:N

    list(i)=i;

    end;

    toc

    %--------------------

    % ---- Snippet 2 ----

    clear all;

    N = 10^7;

    tic;

    list = zeros(1,N);

    for i=1:N

    list(i)=i;

    end;

    toc

    %--------------------

    On my computer, snippet 1 computed about 32 times more slowly than snippet 2.

    By the awesome power of pre-allocation!

    The reason for the discrepancy is due to memory allocation. When you define a variable, Matlab decides how much

    memory is required, and creates a register to store the information. Any floating point number (i.e. any rational

    number, or inf or nan) requires the same amount of space in memory, so if you change the value of list(i) from 0

    to sqrt(2), then the value in the register can simply be overwritten. However, if you decide to append an extra

    value to a list, then a new register needs to be created that is large enough to store the new list. The old register is

    removed.

    In the second expression, we only created a single register, in the step list = zeros(1,N);

    The values in the register were then edited as required, resulting in a tremendous performance improvement.

    Page 19

  • Some useful array operations

    diag(v) if v is a vector, then this command returns a square matrix with vector v on the diagonal, and

    zeros everywhere else. If v is a square matrix then the command returns the vector of values on

    the main diagonal.

    inv(A) gives the matrix inverse of A

    repmat(A,m,n) repeat (tile) array A with m row-wise copies and n column-wise copies

    sum(A,dim) gives the sum of elements in array A along dimension dim (1 for row; 2 for column)

    Character arrays

    Recall that in matlab a string is simply a character array, and can be treated in (largely) the same way as a numeric array with regard to element manipulation. For example, in the program jumble that was demonstrated in week 1, letters in the given character array were repeatedly swapped. Lets try this now with a simple example:

    word = 'Onomatopoeia'; %a very noisy word give_me_a_p = word(8); %get the letter p at position 8 give_me_an_O = word(1); %get the letter O at position 1 word(1)=give_me_a_p; %move the p to position 1 word(8)=give_me_an_O; %move the O to position 8 disp(word) %show word (letters have been switched)

    The result will look a bit strange because of the irregular capitalisation. However, we can change the case of a given

    character (or character array) by using upper or lower:

    word = 'Onomatopoeia'; give_me_a_p = word(8); give_me_an_o = word(1); word(1)=upper(give_me_a_p); word(8)=lower(give_me_an_o); disp(word)

    Sometimes, you may encounter unexpected behaviour when dealing with character arrays. Try out the following expressions, for example:

    isreal('waffles') %tests to see if the input is an array of real numbers my_max('waffles') %uses our own my_max function (see page 15)

    max('waffles') %uses the inbult matlab max function

    These results can be understood by recognising that characters can be encoded using numerical values. We can convert between the numerical and character format by using the functions double and char:

    double('Hello') char([71 111 111 100 98 121 101])

    Cell arrays

    A cell array is similar to a numeric or character array, except that it can contain data of various types and sizes. Cell arrays are denoted by use of braces (curly brackets) in place of the square parentheses that are used for a numeric array. For instance, you can make the following assignment:

    X = {'hello',1,nan(4)};

    Braces are also used to access the items in a cell array. For example:

    X{1}

    X{2}

    X{3}

    X{:}

    You can read more about cell arrays by consulting the matlab documentation here. We will use cell arrays later on in the course.

    Page 20

  • Surface plotting ( = (, ))

    To plot a surface in matlab we can use surf(X,Y,Z), in which Z is an array that holds the values of the surface

    heights at each location defined by X and Y.

    Suppose, for example, that we wish to make a surface plot of the function

    =sin()

    , where = 2 + 2, for , [8,8]

    First, we need to define a grid, consisting of coordinate pairs where we will evaluate (, ).

    In this case, we will choose values for each ordinate and according to

    x=linspace(-8,8,20); %20 x- ordinates

    y=linspace(-8,8,20); %20 y- ordinates

    The next step is to combine x and y into a set of 400 coordinate pairs. This is easiest to achieve by typing:

    [X,Y]=meshgrid(x,y);

    The command creates grid matrices X and Y such that

    Each column of X is the vector of values in x ( = )

    Each row of Y is the vector of values in y ( = )

    Finally, we evaluate

    = ( , )

    For our example, we have

    R=(X.^2+Y.^2).^(1/2);

    Z = sin(R)./R;

    The complete code is shown below

    %CODE

    x=linspace(-8,8,20); y=linspace(-8,8,20);

    [X,Y]=meshgrid(x,y);

    R=(X.^2+Y.^2).^(1/2);

    Z = sin(R)./R;

    surf(X,Y,Z)

    Example: Can you classify the stationary points?

    Note the use of surfc here, which also plots contours in the (x,y) plane

    x=linspace(-1,1,50); y=linspace(-1,1,50); [X,Y]=meshgrid(x,y); Z = 4*X.^2 - 2*X.^4+(X.^6)/4+X.*Y-4*Y.^2+4*Y.^4; surfc(X,Y,Z) xlabel('x') ylabel('y') zlabel('z') title('z = 4x^2-2x^4+0.25x^6+xy-4y^2+4y^4')

    Page 21

  • Example: Parametric plotting

    To construct a surface plot of the torus described by the equations:

    [

    ] = [( + cos ) cos ( + cos ) sin

    sin ],

    , [0,2] = 3, = 1

    R=3; %Distance from centre of tube to centre of torus r=1; %Radius of tube

    theta = linspace(0,2*pi,100); %polar angle phi = linspace(0,2*pi,100); %toroidal angle [T,P] = meshgrid(theta,phi);

    X = (R+r*cos(P)).*cos(T); Y = (R+r*cos(P)).*sin(T); Z = r*sin(P);

    surf(X,Y,Z,'edgecolor','none') %'edgecolor' controls mesh style axis equal %scale the axes

    Contour plots

    Contour plots can be produced in exactly the same way as surface plots, using contour(X,Y,Z) in place of surf(X,Y,Z). For example

    x=linspace(-1,1,50); y=linspace(-1,1,50); [X,Y]=meshgrid(x,y); Z = 4*X.^2 - 2*X.^4+(X.^6)/4+X.*Y-4*Y.^2+4*Y.^4; contour(X,Y,Z,'ShowText','on')

    To control the location of the contours, we can use contour(X,Y,Z,v,'ShowText','on')

    where the vector v contains the contour heights

    Choosing v = [-1,-0.5,0,0.5,1,1.5,2,2.5,3];

    would give the result shown in the figure below.

    Page 22

  • Histograms

    Plotting a histogram for a given data set v in matlab is easy. We simply type:

    hist(v,nbins)

    where nbins is the number of bars that you would like to display on the chart (known as bins or classes). If you do not enter a value for nbins then the default setting of 10 is used.

    However, if you try this for some example data you will see that the

    result is not a proper histogram, because what is shown on the

    vertical axis is the frequency rather than the frequency density.

    %Vector of 10000 numbers drawn from normal

    %distribution with mean 0 and standard

    %deviation 1: v = randn(10000,1); %Histogram of the data, with 100 bins: hist(v,100)

    Fortunately, the hist function also returns the frequencies and bin

    locations as outputs, and so we can re-plot with adjusted values for the

    frequencies:

    [fq,x] = hist(v,100);

    % fq are the frequencies

    % x are the bin centres

    wx = x(2)-x(1);

    % wx is the bin widths (they are all equal)

    %plot the frequency density histogram:

    bar(x,fq/wx,'hist')

    To get the relative frequency density (so that the total area under the curve is 1), we can type

    bar(x,fq/length(v),'hist')

    Page 23

  • 6. Function Handles The inbuilt matlab function quad, allows the area under the curve between = [, ] to be found by typing

    q = quad(f,a,b)

    However, for this to work, matlab must know that f is a function, and so the following expressions would both fail:

    quad(tan,1,4)

    quad(tan(x),1,4)

    In this section, we examine how to use the class attribute to signify a function.

    Being classy

    Recall our earlier discussion about object class. For example, when we create a string

    str='abcdef';

    we can type class(str)to verify that this object is a character array. We will construct objects with the class

    function_handle, beginning with tan as an example. You can type

    ff = @(x)tan(x);

    to create a function handle ff which takes input x and evaluates the result tan(x). To understand the behaviour

    better, try out the following statements:

    class(ff)

    ff(pi/3)

    ff

    The method can be extended to functions of more than one variable. For example

    gg = @(x,y)(x^2+y);

    gg(3,2)

    and is not restricted to scalar-valued functions, as demonstrated by this example:

    hh = @(x)x^2;

    hh([1 2;3 4])

    Below we will create a very boring function, to show how a function handle can be passed as an argument.

    A very boring function

    function out = very_boring(f,X) % out = very_boring(f,X) applies the function handle f to every function in % the array X and returns the result.

    [n,m] = size(X); out = nan(n,m); for i = 1:n*m out(i) = f(X(i)); end;

    Test it: X = magic(4); %Creates a 4x4 array. Why is it magic? very_boring(@(x)(log(x)^-1),X)

    Page 24

  • Declaring a handle for a function

    To declare a handle for an existing function, we can simply prefix the function name with the @ character. For instance,

    f = @tan;

    f(pi/3)

    z = @zeros;

    z(1,3)

    You can do the same thing with your own functions. For instance, if you set your current working directory to the location of the function my_mean that we created in an earlier session, you can type

    m = @my_mean; m(randi([0,9],1,10))

    Function handles for temporary use

    Defining a function handle can also be a quick way of locally defining a function. For example, to define the Heaviside

    step function, which satisfies

    () = {0, < 0

    1, 0

    we can type

    H = @(x)(x>=0);

    A plot of this function is shown below for [1,1].

    x = -1:0.01:-0.01; plot(x,H(x)) hold on; x = 0:0.01:1; plot(x,H(x)) plot(0,0,'o') ylim([-1,2]) set(gca,'FontSize',16) hold off;

    Page 25