Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
<strong>Basic</strong> <strong>Concepts</strong> <strong>in</strong> <strong>Matlab</strong>Michael G. <strong>Kay</strong>Fitts Dept. of Industrial and Systems Eng<strong>in</strong>eer<strong>in</strong>gNorth Carol<strong>in</strong>a State UniversityRaleigh, NC 27695-7906, USAkay@ncsu.eduJanuary 2008Contents1. The <strong>Matlab</strong> Environment 12. Creat<strong>in</strong>g Arrays 13. Sav<strong>in</strong>g and Load<strong>in</strong>g Variables 24. Select<strong>in</strong>g Array Elements 35. Chang<strong>in</strong>g and Delet<strong>in</strong>g Array Elements 36. Manipulat<strong>in</strong>g Arrays 47. Multiplication and Addition 48. Functions and Scripts 69. Anonymous Functions 810. Example: M<strong>in</strong>imum-Distance Location 811. Logical Expressions 912. Cell Arrays, Structures, and N-D Arrays 913. Control Structures 1114. Example: Random Walk Simulation 1315. Logical vs. Index Arrays 1316. Example: The Monti Carlo Method 1417. Full vs. Sparse Matrices 1618. Insert<strong>in</strong>g and Extract<strong>in</strong>g Array Elements 1619. List of Functions Used 161. The <strong>Matlab</strong> EnvironmentAfter launch<strong>in</strong>g <strong>Matlab</strong> (R2007a), a multi-panel w<strong>in</strong>dowappears conta<strong>in</strong><strong>in</strong>g Command W<strong>in</strong>dow, Workspace,Current Directory, and Command History panels, amongothers. This, along with w<strong>in</strong>dows for the Editor/Debugger,Array Editor, Help Browser, etc., that can be <strong>in</strong>voked asneeded, is the <strong>Matlab</strong> environment.<strong>Matlab</strong> has an extensive set of built-<strong>in</strong> functions as well asadditional toolboxes that consist of functions related tomore specialized topics like fuzzy logic, neural networks,signal process<strong>in</strong>g, etc. It can be used <strong>in</strong> two different ways:as a traditional programm<strong>in</strong>g environment and as an<strong>in</strong>teractive calculator. In calculator mode, the built-<strong>in</strong> andtoolbox functions provide a convenient means ofperform<strong>in</strong>g one-off calculations and graphical plott<strong>in</strong>g; <strong>in</strong>programm<strong>in</strong>g mode, it provides a programm<strong>in</strong>g environment(editor, debugger, and profiler) that enables the user to writetheir own functions and scripts.Expressions consist<strong>in</strong>g of operators and functions thatoperate on variables are executed at the command-l<strong>in</strong>eprompt >> <strong>in</strong> the Command W<strong>in</strong>dow. All of the variablesthat are created are stored <strong>in</strong> the workspace and are visible<strong>in</strong> the Workspace panel.Information about any function or toolbox is available viathe command-l<strong>in</strong>e help function (or from the doccommand that provides the <strong>in</strong>formation <strong>in</strong> the HelpBrowser):help sumIn <strong>Matlab</strong>, everyth<strong>in</strong>g that can be done us<strong>in</strong>g the GUI<strong>in</strong>terface (e.g., plott<strong>in</strong>g) can also be accomplished us<strong>in</strong>g acommand-l<strong>in</strong>e equivalent. The command-l<strong>in</strong>e equivalent isuseful because it can be placed <strong>in</strong>to scripts that can beexecuted automatically.2. Creat<strong>in</strong>g ArraysThe basic data structure <strong>in</strong> <strong>Matlab</strong> is the two-dimensionalarray. Array variables can be scalars, vectors, or matrices:• Scalar n = 1 is represented as a 1 × 1 array• Vector a = [1 2 3] is a 1 × 3 array⎡1 2 3 4⎤• Matrix A = ⎢ ⎥ is a 2 × 4 array.⎣5 6 7 8⎦Arrays can be created on the command l<strong>in</strong>e as follows:n = 1n =1a = [1 2 3]a =1
SAVING AND LOADING VARIABLES1 2 3A = [1 2 3 4; 5 6 7 8]A =1 2 3 45 6 7 8In <strong>Matlab</strong>, the case of a variable matters; e.g., the arrays aand A are different variables.To recall the last command executed, press the up-arrowkey ( ↑ ). To suppress the output from a command, end anexpression with a semicolon (;):A = [1 2 3 4; 5 6 7 8];An empty array is considered a 0 × 0 matrix:a = []a =[]The follow<strong>in</strong>g operators and functions can be used toautomatically create basic structured arrays:a = 1:5a =1 2 3 4 5a = 1:2:5a =1 3 5a = 10:-2:1a =10 8 6 4 2a = ones(1,5)a =1 1 1 1 1a = ones(5,1)a =11111a = zeros(1,5)a =0 0 0 0 0The rand function generates random numbers between 0and 1. (Each time it is run, it generates different numbers.)a = rand(1,3)a =0.6086 0.2497 0.8154b = rand(1,3)b =0.2618 0.4760 0.3661A random permutation of the <strong>in</strong>tegers 1 to n can begenerates us<strong>in</strong>g the randperm(n) function:randperm(5)ans =1 3 4 5 2To create a 3 × 3 identity matrix:eye(3)ans =1 0 00 1 00 0 1The variable ans is used as a default name for anyexpression that is not assigned to a variable.3. Sav<strong>in</strong>g and Load<strong>in</strong>g VariablesThe variables currently <strong>in</strong> the workspace are visible <strong>in</strong> theWorkspace panel, or through the whos command:whosName Size Bytes ClassA 2x4 64 double arraya 1x3 24 double arrayans 3x3 72 double arrayb 1x3 24 double arrayn 1x1 8 double arrayGrand total is 24 elements us<strong>in</strong>g 192<strong>by</strong>tesTo save arrays A and a to a file:save myvar A aData files <strong>in</strong> <strong>Matlab</strong> have the extension .mat, so the filemyvar.mat would be saved <strong>in</strong> the current directory (seeCurrent Directory panel). To remove the variables from theworkspace:2
SELECTING ARRAY ELEMENTSclearwhosTo restore the variables:load myvarData files can also be saved and loaded us<strong>in</strong>g the File menu.4. Select<strong>in</strong>g Array ElementsIn <strong>Matlab</strong>, <strong>in</strong>dex arrays <strong>in</strong>side of parenthesis are used toselect elements of an array. The colon operator is used toselect an entire row or column.AA =1 2 3 45 6 7 8A(:,:)ans =1 2 3 45 6 7 8A(1,2)ans =2A(1,:)ans =1 2 3 4A(:,1)ans =15A(:,[1 3])ans =1 35 7The vector [1 3] is an <strong>in</strong>dex array, where each elementcorresponds to a column <strong>in</strong>dex number of the orig<strong>in</strong>almatrix A.The keyword end can be used to <strong>in</strong>dicate the last row orcolumn:A(:,end)ans =48A(:,end-1)ans =37The selected portion of the one array can be assigned to anew array:B = A(:,3:end)B =3 47 8To select the elements along the ma<strong>in</strong> diagonal:diag(B)ans =385. Chang<strong>in</strong>g and Delet<strong>in</strong>g Array ElementsIn calculator mode, the easiest way to change the elementsof an array is to double click on the array’s name <strong>in</strong> theWorkspace panel to launch the Array Editor, which allowsmanual edit<strong>in</strong>g of the array. (The editor can also be used tocreate an array <strong>by</strong> first generat<strong>in</strong>g an array of zeros at thecommand l<strong>in</strong>e and us<strong>in</strong>g the editor to fill <strong>in</strong> the nonzerovalues of the array.)In programm<strong>in</strong>g mode, elements can be changed <strong>by</strong>select<strong>in</strong>g a portion of an array as the left-hand-side target ofan assignment statement:a = 1:5a =1 2 3 4 5a(2) = 6a =1 6 3 4 5a([1 3]) = 0a =0 6 0 4 5a([1 3]) = [7 8]a =7 6 8 4 53
MANIPULATING ARRAYSA(1,2) = 100A =1 100 3 45 6 7 8To delete selected elements of a vector:a(3) = []a =7 6 4 5a([1 4]) = []a =6 4A row or column of a matrix can be deleted <strong>by</strong> assign<strong>in</strong>g itto an empty array:A(:,2) = []A =1 3 45 7 86. Manipulat<strong>in</strong>g ArraysThe follow<strong>in</strong>g operators and functions can be used tomanipulate arrays:AA =1 3 45 7 8A'(Transpose)ans =1 53 74 8fliplr(A)(Flip left/right)ans =4 3 18 7 5flipud(A)(Flip up/down)ans =5 7 81 3 4[A B] (Concatenate matrices)ans =1 3 4 3 45 7 8 7 8[A [10 20]'; 30:10:60]ans =1 3 4 105 7 8 2030 40 50 60A(:)(Convert matrix to column vector)ans =153748A = A(:)'(Convert matrix to row vector)A =1 5 3 7 4 8A = reshape(A,2,3) (Convert back to matrix)A =1 3 45 7 87. Multiplication and AdditionScalarsA scalar can be added to or multiplied with each element ofan array; e.g.,AA =1 3 45 7 82 + Aans =3 5 67 9 104
MULTIPLICATION AND ADDITIONB = 2 * AB =2 6 810 14 16MultiplicationMatrices are multiplied together <strong>in</strong> two different ways:element-<strong>by</strong>-element multiplication, <strong>in</strong>dicated <strong>by</strong> the use of adot (.) along with the operator, and matrix multiplication,where the <strong>in</strong>ner dimensions of the matrices must be thesame; i.e.,Element-<strong>by</strong>-element multiplication: Am× n.∗ Bm× n=C m×nMatrix multiplication: Am× n∗ Bn× p=C m×pC = A .* B (2×3 .* 2×3 = 2×3)C =2 18 3250 98 128A * B (Error: 2×3 * 2×3 ≠ 2×3)??? Error us<strong>in</strong>g ==> *Inner matrix dimensions must agree.C = A * B' (2×3 * 3×2 = 2×2)C =52 116116 276C = A' * B (3×2 * 2×3 = 3×3)C =52 76 8876 116 13688 136 160a = 1:3a =1 2 3a * a' (1×3 * 3×1 = 1×1)ans =14A * a' (2×3 * 3×1 = 2×1)ans =1943Division (./) and power (.^) operators can also bepreformed element <strong>by</strong> element.AdditionMatrices are added together <strong>in</strong> <strong>Matlab</strong> element <strong>by</strong> element;thus, each matrix must be the same size; i.e.,Addition: Am× n+ Bm× n=C m×nC = A + BC =3 9 1215 21 24To add vector a to each row of A, a can be converted <strong>in</strong>to amatrix with the same dimensions as A. This can beaccomplished <strong>in</strong> several different ways:ones(2,1) * a(Matrix multiplication)ans =1 2 31 2 3ones(2,1) * a + Aans =2 5 76 9 11a(ones(2,1),:)(Tony’s Trick)ans =1 2 31 2 3repmat(a,2,1)(Replicate array)ans =1 2 31 2 3Us<strong>in</strong>g repmat is the fastest approach when a is a scalar,while Tony’s Trick is not possible if a does not yet exist andis be<strong>in</strong>g created <strong>in</strong> the expression for the first time.SummationThe elements of a s<strong>in</strong>gle array can be added together us<strong>in</strong>gthe sum and cumsum functions:a = 1:5a =5
FUNCTIONS AND SCRIPTS1 2 3 4 5sum(a)(Array summation)ans =15cumsum(a)(Cumulative summation)ans =1 3 6 10 15By default, <strong>Matlab</strong> is column oriented; thus, for matrices,summation is performed along each column (the 1stdimension) unless summation along each row (the 2nddimension) is explicitly specified:AA =1 3 45 7 8sum(A)ans =6 10 12sum(A,2)(Sum along rows)ans =820sum(A,1)(Sum along columns)ans =6 10 12sum(sum(A))(Sum entire matrix)ans =28Forc<strong>in</strong>g column summation: Even if the default columnsummation is desired, it is useful (<strong>in</strong> programm<strong>in</strong>g mode) toexplicitly specify this <strong>in</strong> case the matrix has only a s<strong>in</strong>glerow, <strong>in</strong> which case it would be treated as a vector and sumto a s<strong>in</strong>gle scalar value (an error):A = A(1,:) (Convert A to s<strong>in</strong>gle-row matrix)A =1 3 4sum(A)(Incorrect)ans =8sum(A, 1)(Correct)ans =1 3 48. Functions and ScriptsFunctions and scripts <strong>in</strong> <strong>Matlab</strong> are just text files with a .mextension. User-def<strong>in</strong>ed functions can be used to extend thecapabilities of <strong>Matlab</strong> beyond its basic functions. A userdef<strong>in</strong>edfunction is treated just like any other function.Scripts are sequences of expressions that are automaticallyexecuted <strong>in</strong>stead of be<strong>in</strong>g manually executed one at a time atthe command-l<strong>in</strong>e. A scripts uses variables <strong>in</strong> the (base)workspace, while each function has its own (local)workspace for its variables that is isolated from otherworkspaces. Functions communicate only through their<strong>in</strong>put and output arguments. A function is dist<strong>in</strong>guishedfrom a script <strong>by</strong> plac<strong>in</strong>g the keyword function as the firstterm of the first l<strong>in</strong>e <strong>in</strong> the file.Although develop<strong>in</strong>g a set of functions to solve a particularproblem is at the heart of us<strong>in</strong>g <strong>Matlab</strong> <strong>in</strong> the programm<strong>in</strong>gmode, the easiest way to create a function is to do it <strong>in</strong> an<strong>in</strong>cremental, calculator mode <strong>by</strong> writ<strong>in</strong>g each l<strong>in</strong>e at thecommand-l<strong>in</strong>e, execut<strong>in</strong>g it, and, if it works, copy<strong>in</strong>g it tothe function’s text file.Example: Given a 2-D po<strong>in</strong>t x and m other 2-D po<strong>in</strong>ts <strong>in</strong>P, create a function mydist.m to determ<strong>in</strong>e the Euclidean(i.e., straight-l<strong>in</strong>e) distance d from x to each of the m po<strong>in</strong>ts<strong>in</strong> P:⎡ p1,1 p1,2⎤x = [ x ] = ⎢ ⎥1 x2, P ⎢ ⎥⎣pm,1 pm,2⎦⎡2 2 ⎤⎢ ( x1− p1,1) + ( x2 − p1,2)⎥d = ⎢⎥⎢2 2 ⎥⎢⎣( x1 − pm,1) + ( x2 − pm,2)⎥⎦The best way to start is to create some example data forwhich you know the correct answer:6
FUNCTIONS AND SCRIPTS515132 x21 3 6x = [3 1];P = [1 1; 6 1; 6 5]P =1 16 16 5The first step is to subtract x from each row <strong>in</strong> P:ones(3,1) * xans =3 13 13 1ones(3,1)*x - Pans =2 0-3 0-3 -4Square each element of the result:(ones(3,1)*x - P) .^ 2ans =4 09 09 16Add the elements <strong>in</strong> each row:sum((ones(3,1)*x - P).^2, 2)ans =43925Then take the square root and assign the result to d:d = sqrt(sum((ones(3,1)*x - P).^2,2))d =235The M-File Editor can be used to create the text file for thefunction mydist. Either select New, M-File from the Filemenu, oredit mydistwhere the editor should appear. Type the follow<strong>in</strong>g twol<strong>in</strong>es (add<strong>in</strong>g a semicolon to the end of the command-l<strong>in</strong>eexpression to suppress output from <strong>in</strong>side the function):function d = mydist(x,P)d = sqrt(sum((ones(3,1)*x - P).^2,2));Save the file, then check to see if <strong>Matlab</strong> can f<strong>in</strong>d the file <strong>by</strong>us<strong>in</strong>g the type command to pr<strong>in</strong>t the function at thecommand l<strong>in</strong>e, and then check to see that it works asdesired:type mydistfunction d = mydist(x,P)d = sqrt(sum((ones(3,1)*x - P).^2,2));d = mydist(x,P)d =235As it is written, the function will work for po<strong>in</strong>ts of anydimension, not just 2-D po<strong>in</strong>ts. For n-dimensional po<strong>in</strong>ts, xwould be a n-element vector and P a m × n matrix; e.g., for4-D po<strong>in</strong>ts:d = mydist([x x],[P P])d =2.82844.24267.0711The only th<strong>in</strong>g “hard-coded” <strong>in</strong> the function is m. Thesize function can be used <strong>in</strong>side the function to determ<strong>in</strong>ethe number of rows (dimension 1) or columns (dimension2) <strong>in</strong> P:7
ANONYMOUS FUNCTIONSm = size(P,1)m =3n = size(P,2)n =2The last th<strong>in</strong>g that should be added to the function is somehelp <strong>in</strong>formation. All of the first block of contiguouscomment l<strong>in</strong>es <strong>in</strong> a function is returned when the helpcommand is executed for the function. Comment l<strong>in</strong>es are<strong>in</strong>dicated <strong>by</strong> an asterisk (%).To get help:help mydistMYDIST Euclidean distance from x to P.d = mydist(x,P)x = n-element vector s<strong>in</strong>gle po<strong>in</strong>tP = m x n matrix of n po<strong>in</strong>tsd = m-element vector, where d(i) =distance from x to P(i,:)The function mydist can now be used <strong>in</strong>side of anyexpression; e.g.,sumd = sum(mydist(x,P))sumd =10If other people will be us<strong>in</strong>g your function, it is a good ideato <strong>in</strong>clude some error check<strong>in</strong>g to make sure the values<strong>in</strong>put to the function are correct; e.g., check<strong>in</strong>g to make surethe po<strong>in</strong>ts <strong>in</strong> x and P have the same dimension.9. Anonymous FunctionsAnonymous functions provide a means of creat<strong>in</strong>g simplefunctions without hav<strong>in</strong>g to create M-files. Givenx = [3 1];P = [1 1; 6 1; 6 5];the sum of the distances from x to each of the po<strong>in</strong>ts <strong>in</strong> Pcan be determ<strong>in</strong>ed <strong>by</strong> creat<strong>in</strong>g a function handle sumMydistto an anonymous function:sumMydist = @() sum(mydist(x,P));sumMydistsumMydist =@() sum(mydist(x,P))sumMydist()ans =10The values of x and P are fixed at the time sumMydist iscreated. To make it possible to use different values for x:sumMydist = @(x) sum(mydist(x,P));sumMydist([6 1])ans =9sumMydist([4 3])ans =9.262410. Example: M<strong>in</strong>imum-Distance LocationAnonymous functions can be used as <strong>in</strong>put arguments toother functions. For example, fm<strong>in</strong>search performs generalpurposem<strong>in</strong>imization. Start<strong>in</strong>g from an <strong>in</strong>itial location x 0 , itcan be used to determ<strong>in</strong>e the location x that m<strong>in</strong>imizes thesum of distances to each po<strong>in</strong>t <strong>in</strong> P:x0 = [0 0];[x,sumd] = fm<strong>in</strong>search(sumMydist,x0)x =5.0895 1.9664sumd =8.6972For this particular location problem, any <strong>in</strong>itial location canbe used to f<strong>in</strong>d the optimal location because the objective isconvex:[x,sumd] = fm<strong>in</strong>search(sumMydist,[10 5])8
LOGICAL EXPRESSIONSx =5.0895 1.9663sumd =8.6972For many (non-convex) problems, different <strong>in</strong>itial start<strong>in</strong>gvalues will result <strong>in</strong> different (locally optimal) solutions.11. Logical ExpressionsA logical array of 1 (true) and 0 (false) values is returned as aresult of apply<strong>in</strong>g logical operators to arrays; e.g.,a = [4 0 -2 7 0]a =4 0 -2 7 0a > 0(Greater than)ans =1 0 0 1 0a == 7(Equal to)ans =0 0 0 1 0a ~= 0(Not equal to)ans =1 0 1 1 0(a >= 0) & (a 4) (Logical OR)ans =0 0 1 1 0~((a < 0) | (a > 4)) (Logical NOT)ans =1 1 0 0 1A logical array can be used just like an <strong>in</strong>dex array to selectand change the elements of an array; e.g.,a(a > 0)ans =4 7a(a == 7) = 8a =4 0 -2 8 0a(a ~= 0) = a(a ~= 0) + 1a =5 0 -1 9 012. Cell Arrays, Structures, and N-D ArraysCell ArraysA cell array is a generalization of the basic array <strong>in</strong> <strong>Matlab</strong>that can have as its elements any type of <strong>Matlab</strong> datastructure. Curly braces, { }, are used to dist<strong>in</strong>guish a cellarray from a basic array.Unlike a regular matrix, a cell array can be used to storerows of different lengths:c = {[10 20 30],[40],[50 60]}c =[1x3 double] [40] [1x2 double]The <strong>in</strong>dividual elements <strong>in</strong> the cell array are each a rowvector that can be accessed as follows:c{1}ans =1 2 3To access the elements with<strong>in</strong> each row:c{1}(1)ans =10To add an element to the end of the first row:c{1}(end+1) = 35c =[1x4 double] [40] [1x2 double]c{1}ans =10 20 30 35To add another row to the end of the cell array:c(end+1) = {1:2:10}c =[1x4 double] [40] [1x2 double][1x5 double]c{end}ans =1 3 5 7 99
CELL ARRAYS, STRUCTURES, AND N-D ARRAYSA common use for cell arrays is to store text str<strong>in</strong>gs:s = {'Miami','Detroit','Boston'}s ='Miami' 'Detroit' 'Boston'Some functions can accept a cell array as <strong>in</strong>put:s = sort(s)s ='Boston' 'Detroit' 'Miami'A cell array can be used to store any type of data, <strong>in</strong>clud<strong>in</strong>gother cell arrays. One use of a cell array is to store all of the<strong>in</strong>put arguments for a function:xP = {x, P}xP =[1x2 double] [3x2 double]The arguments can then be passed to a function <strong>by</strong>generat<strong>in</strong>g a comma-separated list from the cell array:d = mydist(xP{:})d =235Cell arrays of can be created us<strong>in</strong>g the cell function:c = cell(1,3)c =[] [] []Non-empty values can then be assigned to each elementus<strong>in</strong>g a FOR Loop (see Section 13 below).A cell array can be both created and assigned non-emptyvalues <strong>by</strong> us<strong>in</strong>g the deal function:[c2{1:3}] = deal(0)c2 =[0] [0] [0][c3{1:3}] = deal(1,2,3)c3 =[1] [2] [3]StructuresStructures are used to group together related <strong>in</strong>formation.Each element of a structure is a field:s.Name = 'Mike's =Name: 'Mike's.Age = 44s =Name: 'Mike'Age: 44Structures can be comb<strong>in</strong>es <strong>in</strong>to structure arrays:s(2).Name = 'Bill's =1x2 struct array with fields:NameAges(2).Age = 40;s(2)ans =Name: 'Bill'Age: 40s.Nameans =Mikeans =BillAn alternate way to construct a structure array is to use thestruct function:s =struct('Name',{'Mike','Bill'},'Age',{44,40})s =1x2 struct array with fields:NameAgeWhen needed, the elements <strong>in</strong> each field <strong>in</strong> the array can beassigned to separate arrays:names = {s.Name}names ='Mike' 'Bill'ages = [s.Age]ages =44 4010
CONTROL STRUCTURESAn alternate way to do the same th<strong>in</strong>g that is sometimesmore efficient is to use a s<strong>in</strong>gle structure <strong>in</strong>stead of an arrayof structures and use an array for each field of the structure:t.Name = {'Mike','Bill'}t =Name: {'Mike' 'Bill'}t.Age = [44 40]t =Name: {'Mike' 'Bill'}Age: [44 40]N-D ArraysMultidimensional, or N-D, arrays extend the basic 2-D arrayused <strong>in</strong> <strong>Matlab</strong>. N-D arrays cannot be stored as sparsearrays, so they should only be used for dense arrays. N-Darray can be created <strong>by</strong> extend<strong>in</strong>g a 2-D array or <strong>by</strong> directlycreat<strong>in</strong>g the array us<strong>in</strong>g functions like zeros and ones:D3 = [1 2 3; 4 5 6]D3 =1 2 34 5 6D3(:,:,2) = [7 8 9; 10 11 12]D3(:,:,1) =1 2 34 5 6D3(:,:,2) =7 8 910 11 12To access <strong>in</strong>dividual elements and cross-sections:D3(1,3,2)ans =9D(:,1,:)ans(:,:,1) =14ans(:,:,2) =710To convert the 3-D answer to a 2-D array:D2 = squeeze(D(:,1,:))D2 =1 74 1013. Control StructuresIn <strong>Matlab</strong>, FOR loops iterate over the columns of an array,and logical expressions are used for conditional evaluation<strong>in</strong> IF statements and WHILE loops.FOR Loopfor i = 1:3iendi =1i =2i =3for i = 5:-2:1, i, endi =5i =3i =1Any type of array can be used; e.g., a character array:chararray = 'abc'chararray =abcfor i = chararrayiendi =ai =b11
CONTROL STRUCTURESi =cBecause any type of array can be used <strong>in</strong> a FOR loop, us<strong>in</strong>gFOR loops can greatly slow down the execution speed of<strong>Matlab</strong> as compared to the equivalent array operation(although FOR loops with only scalar arithmetic <strong>in</strong>side havebeen optimized <strong>in</strong> Release 13 of <strong>Matlab</strong> so that there is noperformance penalty).Most of the standard arithmetic operations and functions <strong>in</strong><strong>Matlab</strong> cannot be directly applied to an entire cell array;<strong>in</strong>stead, a FOR loop can used to apply the operation orfunction to each element of the cell array:c = {[10 20 30],[40],[50 60]}c =[1x3 double] [40] [1x2 double]c = c + 1??? Error us<strong>in</strong>g ==> +Function '+' is not def<strong>in</strong>ed for valuesof class 'cell'.for i = 1:length(c), c{i} = c{i} + 1;endThe function length is equal to max(size(c)). Tosee the contents of each element <strong>in</strong> cell array:c{:}ans =11 21 31ans =41ans =51 61IF Statementn = 3;if n > 0disp('Positive value.')elseif n < 0disp('Negative value.')elsedisp('Zero.')endPositive value.WHILE Loopwhile n > 0n = n - 1endn =2n =1n =0DO-WHILE Loopdone = 0;while ~donen = n + 1if n >= 3, done = 1; endendn =1n =2n =3The DO-WHILE loop is used to ensure that the statements<strong>in</strong>side the loop are evaluated at least once even if the logicalexpression is not true.The logical expression <strong>in</strong> a conditional statement mustevaluate to a s<strong>in</strong>gle logical scalar value. To convert a logicalvector to a scalar, the functions any and all can be used:a = [5 0 -1 9 0];a > 0ans =1 0 0 1 0any(a > 0)ans =1all(a > 0)ans =012
EXAMPLE: RANDOM WALK SIMULATION14. Example: Random Walk SimulationThe follow<strong>in</strong>g example simulates a random walk. Start<strong>in</strong>gfrom the orig<strong>in</strong> at 0, there is a 50–50 chance that the nextstep is up one unit of distance (+1) or down one unit ofdistance (–1). The vector d represents the cumulativedistance from the orig<strong>in</strong> at each step:Start <strong>by</strong> us<strong>in</strong>g only 5 steps (and, to get the same randomnumbers as show below, the state of the random numbergenerator can first be set to some arbitrary number like123).rand('state',123)s = rand(1,5)s =0.0697 0.2332 0.73740.7585 0.6368s > 0.5ans =0 0 1 1 1(s > 0.5)*2ans =0 0 2 2 2((s > 0.5)*2) - 1ans =-1 -1 1 1 1d = cumsum(((s > 0.5)*2) - 1)d =-1 -2 -1 0 1Now <strong>in</strong>crease to 100 steps (and use semicolon so output issuppressed):s = rand(1,100);d = cumsum(((s > 0.5)*2) - 1);plot(d)6420-2-4-60 10 20 30 40 50 60 70 80 90 100Multiple runs of the simulation can be used to verify thetheoretical estimate of the expected distance from the orig<strong>in</strong>after t steps, where d(t) is the last element of d:2tE ⎡⎣dt() ⎤⎦ →πA FOR-loop can be used iterate through 100 runs of a1,000 step random walk:for i = 1:100d = cumsum(((rand(1,1000)>0.5)*2)-1);dt(i) = d(end);endmean(abs(dt))(Sample mean)ans =24.2200This compares with the theoretical estimate:2(1, 000)= 25.2313π15. Logical vs. Index ArraysLogical arrays and <strong>in</strong>dex arrays provide alternative means ofselect<strong>in</strong>g and chang<strong>in</strong>g the elements of an array. The f<strong>in</strong>dfunction converts a logical array <strong>in</strong>to an <strong>in</strong>dex array:aa =5 0 -1 9 0ispos = a > 0(Logical array)ispos =13
EXAMPLE: THE MONTI CARLO METHOD1 0 0 1 0a(ispos)ans =5 9idxpos = f<strong>in</strong>d(a > 0)(Index array)idxpos =1 4a(idxpos)ans =5 9Some functions return logical or <strong>in</strong>dex arrays:s = {'Miami','Detroit','Boston'};idxDetroit = strmatch('Detroit',s)idxDetroit =2isDetroit = strcmpi('detroit',s)isDetroit =0 1 0Although similar, the use of logical and <strong>in</strong>dex arrays havedifferent advantages:Advantages of Logical Arrays1. Direct address<strong>in</strong>g: It is easy to determ<strong>in</strong>e if <strong>in</strong>dividualelements of the target array satisfy the logicalexpression; e.g., a value of 1 (true) for ispos(4)directly determ<strong>in</strong>es that a(4) is positive, while itwould be necessary to search through each element ofidxpos to determ<strong>in</strong>e if 4 is an element of the array(i.e., any(idxpos == 4)).2. Use of logical vs. set operators: When compar<strong>in</strong>g multiplelogical arrays, logical operators like & (AND), | (OR),and ~ (NOT) can be used <strong>in</strong>stead of the morecumbersome set operator functions like <strong>in</strong>tersect,union, and setdiff that are necessary if <strong>in</strong>dexarrays are comb<strong>in</strong>ed.Advantages of Index Arrays1. Order <strong>in</strong>formation: Unlike logical arrays, the order of theelements <strong>in</strong> an <strong>in</strong>dex array provides useful <strong>in</strong>formation;e.g., the <strong>in</strong>dex array idxa returned <strong>by</strong> the functionsort <strong>in</strong>dicates the sorted order of the orig<strong>in</strong>alunsorted array a:aa =5 0 -1 9 0[sa, idxa] = sort(a)sa =-1 0 0 5 9idxa =3 2 5 1 42. Duplicate values: An <strong>in</strong>dex array can have multipleelements with the same <strong>in</strong>dex value, allow<strong>in</strong>g arrays tobe easily manipulated; e.g.,idx = [1 2 1];a(idx)ans =5 0 53. Space-sav<strong>in</strong>g: If only a few elements of the target arrayare be<strong>in</strong>g considered, then an <strong>in</strong>dex array need onlystore these elements, <strong>in</strong>stead of a logical array that isequal <strong>in</strong> size to the target array; e.g., the <strong>in</strong>dex arrayidxm<strong>in</strong>a has only a s<strong>in</strong>gle element:[m<strong>in</strong>a, idxm<strong>in</strong>a] = m<strong>in</strong>(a)m<strong>in</strong>a =-1idxm<strong>in</strong>a =316. Example: The Monti Carlo MethodThe Monti Carlo method is a general-purpose simulationtechnique that uses random numbers to estimate thesolutions to problems that are too difficult to solveanalytically or <strong>by</strong> us<strong>in</strong>g other, more specialized,approximation techniques. It differs from other types ofsimulation because it is used for static problems where timeis not <strong>in</strong>volved.In this example * , the value of pi will be estimated <strong>by</strong>determ<strong>in</strong><strong>in</strong>g the number m out of n po<strong>in</strong>ts that fall with<strong>in</strong> aunit circle (r = 1). The probability that a po<strong>in</strong>t (x, y)randomly generated <strong>in</strong>side a square is also <strong>in</strong>side the circle isequal to the ratio of area of the circle and the square:2 2 Acircleπr π mPx ( + y < 1) = = = ≈A 4 4 nsquare* Adapted from A. Csete, http://www.daimi.au.dk/~u951581/pi/MonteCarlo/pi.MonteCarlo.html.214
EXAMPLE: THE MONTI CARLO METHODPi can then be estimated as π = 4m n .-11-1The Monti Carlo method can be implemented <strong>in</strong> <strong>Matlab</strong> asfollows, start<strong>in</strong>g with a small number of po<strong>in</strong>ts (n = 3) whilethe code is be<strong>in</strong>g developed and then switch<strong>in</strong>g to a largernumber to actually estimate pi (to get the same randomnumbers as show below, the state of the random numbergenerator can first be set to some arbitrary number like123):rand('state',123)n = 3;XY = rand(n,2)XY =0.0697 0.75850.2332 0.63680.7374 0.6129XY = XY * 2 - 1XY =-0.8607 0.5171-0.5335 0.27370.4749 0.2257is<strong>in</strong> = sum(XY .^ 2, 2) < 1is<strong>in</strong> =011m = sum(is<strong>in</strong>)m =21piestimate = 4 * m/npiestimate =2.6667pians =3.1416Now that it is work<strong>in</strong>g, n can be <strong>in</strong>creased (along withadd<strong>in</strong>g semicolons to the end of statements) and the resultsplotted:n = 5000;XY = rand(n,2) * 2 - 1;is<strong>in</strong> = sum(XY .^ 2, 2) < 1;m = sum(is<strong>in</strong>)m =3967piestimate = 4 * m/npiestimate =3.1736pians =3.1416To plot results:plot(XY(is<strong>in</strong>,1),XY(is<strong>in</strong>,2),'b.')axis equalThe commands used <strong>in</strong> this example could be copied to theM-File Editor and saved as a script, e.g., montipi.m. Thescript could then be executed <strong>by</strong> typ<strong>in</strong>g montipi at thecommand prompt.15
FULL VS. SPARSE MATRICES17. Full vs. Sparse MatricesIn many applications, only a small number of the elementsof a matrix will have nonzero values. For efficiency, thesematrices can be stored as sparse matrices <strong>in</strong>stead of asnormal full matrices; e.g.,A = [0 0 0 30; 10 0 20 0]A =0 0 0 3010 0 20 0sparse(A)ans =(2,1) 10(2,3) 20(1,4) 30full(A)ans =0 0 0 3010 0 20 018. Insert<strong>in</strong>g and Extract<strong>in</strong>g Array ElementsInsert<strong>in</strong>g Into a New MatrixThe sparse function can be used to create a 2 × 3 matrix Awith nonzero values A(1,4) = 30, A(2,1) = 10, and A(2,3) =20:A = sparse([1 2 2], [4 1 3], [30 1020], 2, 4)A =(2,1) 10(2,3) 20(1,4) 30Insert<strong>in</strong>g Into an Exist<strong>in</strong>g MatrixIf a 2 × 3 matrix B exists, new values can be <strong>in</strong>serted <strong>in</strong>to B<strong>by</strong> first creat<strong>in</strong>g a sparse matrix with the same size as B withnonzero values correspond<strong>in</strong>g to the elements to be<strong>in</strong>serted <strong>in</strong> B; e.g., to <strong>in</strong>sert the nonzero values of A <strong>in</strong>to B:B = [1:4; 5:8]B =1 2 3 45 6 7 8B(A ~= 0) = A(A ~= 0)B =1 2 3 3010 6 20 8Extract<strong>in</strong>g From a MatrixThe (1,4), (2,1), and (2,3) elements of B can be extracted tothe vector b as follows:B([1 2 2],[4 1 3])ans =30 1 38 10 208 10 20b = diag(B([1 2 2],[4 1 3]))b =30102019. List of Functions UsedThe follow<strong>in</strong>g basic <strong>Matlab</strong> functions were used <strong>in</strong> thispaper:deal length sortdiag load sparsedisp mean sqrtdoc m<strong>in</strong> squeezeeye ones strcmpif<strong>in</strong>d rand strmatchfliplr randperm structflipud repmat sumfm<strong>in</strong>search reshape typefull save whoshelp size zeros16