You are on page 1of 37

1 MATLAB ESSENTIALS

1.1 BASICS
1.1.1 1.1.2 1.1.3 1.1.4 1.1.5 1.2.1 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6

PHYS100
2 2 8 9 10 12 15 16 18 21 23 25 26 27 28 29 29

Start and Termination of a MATLAB Session Desktop Environment Saving Variables and Command Window Session & Variables Floating-Point (Real) Numbers Additional MATLAB Data Classes Creation of Vectors Functions to Manipulate Vectors, Matrices, and Arrays Extract Elements via Subscripts and Colon Operators Arithmetic Operators Relational Operators Logical Operators

1.2 MATRICES AND VECTORS

1.3 FUNCTIONS
1.3.1 M Files 1.3.2 Anonymous Functions 1.3.3 Passing Functions as Arguments to other Functions

1.4 FLOW CONTROL


1.4.1 if-end Expressions 1.4.2 for Loops 1.4.3 while Loops

1.5 PLOTS
1.5.1 Structure of a MATLAB Plot 1.5.2 Interactive Plotting 1.5.3 Creation of Simple Plots via Command Line 1.5.4 Generation of Multiple Curves in a Single Plot Frame 1.5.5 Plots of Functions 1.5.6 How to Save a Figure 31 31 35 35 36 36
37

1.6 TIPS FOR BEGINNERS 1.7 REFERENCES

37

1 MATLAB BASICS
The term MATLAB is an acronym for the phrase MATrix LABoratory, a software product originally created by Cleve Moler in the late 1970s as a user friendly interface to numerical libraries for linear algebra. Unlike Mathematica and Maple, which emphasize the manipulation of symbolic expressions, the focus of MATLAB is computation. The central MATLAB variable is a real-number matrix, and, hence, all numerical results are potentially inexact due to rounding errors which exist at the core of computer arithmetic. However, MATLAB is more than a computer language -- it is an interactive problem solving environment for performing numerical computations. It primary strengths are rapid code prototyping and data manipulation due to its strengths in matrix computations and graphics. It is excellent environment investigating for small and medium scale problems (e.g., Kelley, 2003). Since it is an interpreted language, its primary weakness is its slow execution speed compared to the execution speed of compiled languages such as Fortran and C++. The font convention in these handouts is that my text is typed in 10 pt Sans Serif, but MATLAB commands and responses are typed in bold 10pt Courier font.

1.1.1) How to Start & Terminate MATLAB Sessions:


Start MATLAB by double clicking on the icon labeled MATLAB in the All Programs menu. Terminate a MATLAB session in any of three ways: 1) type Ctrl q simultaneously on the keyboard, OR, 2) click Exit MATLAB, the final entry of the File menu, OR, 3) type quit or exit at the command prompt (>>) in the Command Window. NOTE: The workspace is not maintained across MATLAB sessions. When you quit MATLAB, by default, the workspace is cleared and all your data is lost.

1.1.2) Desktop Environment see figure on page 4:


The sizes of these windows and their locations on the screen, as well as well as what windows to view are all customizable via the Desktop Layout tab under the Desktop icon on the MATLAB toolbar. To change the layout read chapter 2 of MATLAB@ 7 Desktop Tools and Development Environment (matlab_env.pdf), which I have placed in the mathworks directory on the class site. Command Window: <= Large panel in the middle of the figure. The prompt >> (and flashing vertical bar) in the Command Window indicates that MATLAB is ready to accept input from you. When you see the >> prompt, you can enter a number, a variable or a name of a function, via the keyboard. When you press the Enter or Return key after typing a line, MATLAB displays what you have typed as well as the result: >> 6*7 ans = 42 If you do not assign a variable name to your calculation, such as above, MATLAB assigns the default name, ans, to your result. If the variable ans existed before you typed 6*7, the previous value of ans is overwritten by 42. By default MATLAB inserts a blank line between a command and the display of the result of a command. To suppress such blank lines in the Command Window one types, >> format compact >> 6*7

ans = 42 Alternatively, to suppress such blank lines permanently change the Numeric display setting to compact on the Preferences page found under the File tab. Note also to save space when I insert MATLAB results into Word documents, I move MATLAB answers to the line ans =. One can place multiple commands on a single line by separating them by commas >> cos(0.0), cos(pi/4.0) ans = 1 ans = 0.7071 Employ the = symbol to assign values to variables >> x = exp(2), y = cos(0.25*pi), z = x + y x = 7.3891 y = 0.7071 z = 8.0962 Variable Names. All variable names must: Start with a letter. Consist of letters (a-z, A-Z), digits (0-9), and underscore (_), MATLAB distinguishes UPPER & lower case letters. Can contain a maximum of 63 characters. Cannot contain blanks. Some built-In MATLAB variables are: pi i, j Inf NaN 3.14159265358979 (-1.0)0.5 result of n/0, where n is any non-zero real number Not a number, created by 0/0 or 0*Inf,

MATLAB has reserved keywords which cannot be used as variable names. These keywords can be identified by typing ->> iskeyword break case catch classdef continue else elseif end for function global if otherwise parfor persistent return spmd switch try while MATLAB displays variables in floating point notation:

3.782x1011 is represented as 3.782e+11.

Integer powers of ten indicated by the XX values in e+XX, e+XX represents 10XX & NOT 2.7183XX. You cannot employ fractional powers of ten -- you cannot use 3.46e9.5.
NOTE: the following format is legal but do not use 3.56*10^9, specify a number as 3.59e9! Current Directory tab: Please note the name of this directory when you start a MATLAB session. You probably do not have permission to create files in the default directory on the machines in academic computing centers. When MATLAB creates/reads a file, the default behavior is to do so from the current directory and the directories which constitute the path. The path can be customized employing the Set Path command found under the File tab. Suppression of screen output. The default MATLAB behavior is to display all the output to the Command window, which can lead to considerable clutter when working with arrays. Placing a semicolon at the end of a command, before you click the Enter key, suppresses the screen output. Inserting comments use %. All text on a line following the % symbol is ignored by MATLAB. Line continuation. Three or more periods placed at the end of a line indicates the continuation of the expression on the next line in the Command Window environment.

Workspace Browser: <= small panel on the upper right. The Workspace browser shows the properties of currently defined variables. It is empty at startup. The name of each variable, its array size, and its size in bytes are listed. A function alternative for this panel is to type whos in the Command Window.

Note that the workspace is not maintained across MATLAB sessions. When you quit MATLAB, the workspace is destroyed. To save all the workspace variables, from the File menu (the top of MATLAB window), select Save Workspace As, OR click the save button (the floppy disk icon 4th icon over) in the Workspace browser toolbar. You can use the Variable Editor in the Workspace panel to inspect the contents of arrays. Highlight relevant variable in the Workspace by clicking on it. Or click the open selection button (graph with pencil), 2nd item on the toolbar. Alternatively, you can open the Array Editor from the Command Window by typing openvar with the name, surrounded by single quotes, of the variable you want to inspect.

Command History: <= small panel on the lower right. Unlike the Workspace window, the record of commands you create remains on your computer across all MATLAB sessions. You can view a log of the commands and functions you have entered in previous sessions. Note a timestamp marks the beginning of each MATLAB session. Double-click any entry (entries) in the Command History window to execute that statement(s). Alternatively, you can create m-files from such commands. Right-click the selection and click Create m-files from the context menu. Employ the Help Window Navigator, to be discussed shortly, to provide the details to use the Command History.

Editor/Debugger: [Not shown in the Desktop Environment figure.] Rather than type repeatedly MATLAB commands, you can create files of these MATLAB commands and then activate them as a single file. The name of such command files must end with .m file extension. To create a new m-file in the Editor/Debugger, either click the new file icon (the white rectangle with a red dot in the upper left corner and the upper right corner folded over) on the MATLAB toolbar, OR select File -> New -> M-file from the MATLAB toolbar. Alternatively, type edit in the Command Window. To open an existing M-file in the Editor/Debugger, click the open button icon (open folder) on the toolbar (2nd line) or select File -> Open. The Open dialog box appears, listing all MATLAB files in the work space directory. Once you have finished typing your commands, save the file via the Save command under the File tab, OR click the blue floppy disk icon. You can run your file in the Editor/Debugger window by clicking the execute icon (solid green triangle superimposed on pale blue square). Alternatively, you can run your m-file in the Command Window by typing its name (without the .m extension) and hitting the Enter key.

Mathworks offers you several options for accessing help while running MATLAB. Help Browser: To open the help browser: click on the Help tab on the top toolbar, OR, click the help button blue-circled ? symbol (immediately below the Help tab), OR, type helpbrowser in the Command Window.

NOTE that the tabs in the Help Window Navigator (shown below) provide different ways to search for information: contents, index, or search.

Their second on-line option is the function browser. MathWorks has added their new help tool, as of MATLAB 7.7.0 (R2008b), It is easy to miss! It is activated by clicking the fx symbol to the immediate left of the active command prompt, >> and a screen similar to that below appears

Mathworks third option for accessing help while running MATLAB is type >> help name_of_function in the Command Window environment. If you do not know/remember the name of the function you can type >> lookfor name_of_function Finally, you can access MathWorks website from MATLAB under the Help tab => Web Resources => The MathWorks Web Site.

Finally, for those of you who prefer to read manuals, I have placed in the mathworks directory of the class site the following manuals for MATLAB 7.8.0 (R2009a):

MATLAB@ 7 Getting Started Guide (getstart.pdf) MATLAB@ 7 Desktop Tools and Development Environment (matlab_env.pdf) MATLAB@ 7 Mathematics (math.pdf) MATLAB@ 7 Programming Fundamentals (matlab_prog.pdf) MATLAB@ 7 Programming Tips (programming_tips.pdf) MATLAB@ 7 Object-Oriented Programming (matlab_oop.pdf) MATLAB@ 7 Data Analysis (data_analysis.pdf) MATLAB@ 7 Graphics (graphg.pdf) MATLAB@ 7 3D Visualization (visualize.pdf) MATLAB@ 7 Function Reference: A-E (refbook.pdf) MATLAB@ 7 Function Reference: F-O (refbook2.pdf) MATLAB@ 7 Function Reference: P-Z (refbook3.pdf)
An Additional MATLAB Resource: Electronic Resources at http:/libraries.claremont.edu

(260 pg.) (957 pg.) (443 pg.) (837 pg.) (65 pg.) (437 pg.) (216 pg.) (671 pg.) (212 pg.) (1378 pg.) (1732 pg.) (1802 pg.)

A Guide to MATLAB for Beginners and Experienced Users 2nd Ed. Brian R. Hunt, Ronald L. Lipsman,
Jonathan M. Rosenberg, with Kevin R. Coombes, John E. Osborn, and Garrett J. Stuck, 2006, (Cambridge University Press: Cambridge, UK).

1.1.3) Saving a Command-Window Sessions & Variables:

a) First you can save all the command text input/output in the command window to a file via the diary command. b) Second you can save the variables you have created during a MATLAB session to a separate file via the save command.

To save a copy of all the commands you will type as well as the resulting screen output, type at the beginning of a MATLAB session, at the prompt, >> diary('Name_of_file'). Dont forget to do this! All subsequent commands and outputs will be copied to the text file named, Name_of_file. NOTE that if you type ONLY >> diary your subsequent commands and returning outputs will be copied to a file named diary. NOTE: the diary command does not save graphics and variables. To turn off diary storage, type >> diary off To turn on diary storage type >> diary on

Hint: appropriate use of the diary command is an excellent way to create home works and tests. To save all the workspace variables for later use, at the end of a session, type in the Command Window >> save name_of_file All the variables are stored in a binary (machine-readable not text readable) file called name_of_file.mat. If you type >> save All the variables are store in a file with the default name, matlab.mat. If you type at the prompt >> save name_of_file_2 x y z only the variables x, y, and z are saved in a file named name_of_file_2.mat. To retrieve the variables in another MATLAB session, type at the prompt >> load name_of_file You do not need to use the extension .mat -- .mat is assumed.

1.1.5 Floating-Point (REAL) Numbers


By default, every real number is represented by double precision IEE 754 format- every number is defined by 64 base-2 digits. This representation does NOT employ the familiar base 10 notation. The following three parameters are helpful in understanding the limitations of binary number representation.

Precision: It is the smallest positive number, eps, such that MATLAB can distinguish (1 + eps) from eps. This value, eps, indicates the precision, or smallest possible relative error, at which calculations are performed
>> eps ans = 2.2204e-016 The fundamental parameter eps also represents between a number and the next greatest positive number. Thus MATLAB executes elementary arithmetic operations for double class variables with ~16 decimal digits of accuracy. The greatest number one can create in MATLAB is realmax. In decimal notation it is >> realmax(double) ans = 1.797693134862316e+308 Numbers greater than this value can be created easily by accident (divide any positive or negative number by 0) and result in what is termed OVERFLOW and the values are set to infinity, represented by the symbol Inf > >> 10.0/0.0, -10.0/0.0 ans = Inf ans = -Inf

mal digits, BUT only 16 decimal digits are significant! For example,
>> realmax(double) ans = 1.797693134862316e+308 >> realmax (double)+ 1.0e291 ans = 1.797693134862316e+308

Please observe that overflows do not halt calculations. Although numbers can possess up to 308 deci-

>> realmax(double) + 9.0e291 ans = 1.797693134862316e+308 >> realmax(double) + 1.0e292 ans = Inf The behavior of small numbers is different. There exists a parameter called realmin, >> realmin(double) ans = 2.225073858507201e-308 Realmin is the smallest floating-point number one can create with16 decimal digit accuracy. Such numbers are termed normal double-precision variables. Note you create numbers smaller than realmin, but at the cost of greatly reduced precision. However numbers less than eps*realmin are set to zero. Complex Numbers: Complex numbers can be created simply from the function complex >> z = complex(rand(4,1), rand(4,1)) z = 0.7094 + 0.6551i 0.7547 + 0.1626i 0.2760 + 0.1190i 0.6797 + 0.4984i >> size(z) ans = 4 1 where i = (-1.0)0.5. Please use the function browser, fx, to identify some of the many intrinsic MATLAB functions which operate on complex numbers >> real(z)' ans = 0.7094 0.7547 0.2760 0.6797 >> imag(z)' ans = 0.6551 0.1626 0.1190 0.4984 >> ctranspose(z) ans =0.7094 - 0.6551i 0.7547 - 0.1626i 0.2760 - 0.1190i 0.6797 - 0.4984i >> conj(z) ans = 0.7094 0.7547 0.2760 0.6797 >> class(z) ans = double Note that complex numbers do NOT constitute a distinct data class. Such numbers by default store their real and imaginary components in double precision. 0.6551i 0.1626i 0.1190i 0.4984i

1.1.5 Additional MATLAB Data Classes


MATLAB employs other classes of variables, beyond the 64-bit class double: (e.g. [p. 40] Higham & Highhan 2005) single - The use of the function, single(A), converts a numeric variable to the single 32-bit format. The major reasons for employing the single class are to save the storage of real data and investigate errors in algorithm by employing both single and double arithmetic. As seen immediately below, the use of the single data type reduces greatly the range and precision of floating point numbers. Since the employ-

10

ment of single precision does not lead to a significant speed advantage, it use in coding is not recommended. >> realmax('single') ans = 3.4028e+038 >> realmin('single') ans = 1.1755e-038 >> eps('single') ans = 1.1921e-007 logical This data type possesses only values of either 0 or 1. More significantly, logical arrays are also created by the relational operators (==,<,>,~, etc.) and functions like any, all, isnan, isinf, and isfinite. intXXX - MATLAB can create and manipulate integer variables with eight integer format lengths, both signed (int8, int16, int32, int64) and unsigned (uint8, uint16, unit32, unit64). MATLAB possesses limited arithmetic operations to manipulate this class of numeric data: its primary is the efficient storage of images. >> [intmin('int8') intmax('int8')] ans = -128 127 >> [intmin('uint8') intmax('uint8')] ans = 0 255 >> [intmin('int32') intmax('int32')] ans = -2147483648 2147483647 Note the unusual behavior that integers created outside their designated range do NOT generate underflows/overflows (0, Inf), as found for floating-point numbers, but instead map to the ends of their range >> [int8(-130) int8(130)] ans = -128 127 char - String arrays are created by placing single quotes around characters or by applying the char function to 65 to 90 to create the capitals A:Z and 97 to 122 to create the lower case, a:z. MATLAB has a number of built-in functions for manipulating strings. >> s = 'name of city' s = name of city >> char([67 80 81]) ans = CPQ cell - This data type yields one approach for creating collections of cells in which one can store different classes of data. Cell components are accessed via array indexing employing curly braces, {}. >> B = { [1 2 3], 'data', int8(66) } B = [1x3 double] 'data' [66] >> class(B) ans = cell struct This data type is another approach for producing multidimensional objects where elements, composed of different data types, are accessed by field designators. In the following a scalar structure is created with three fields >> >> >> >> S.name = 'john smith'; S.score= 89; S.grade= 'B+'; class(S)

11

ans = struct >> S S = name: 'john smith' score: 89 grade: 'B+'

1.2 MATRICES, ARRAYS, AND VECTORS


1.2.1 Creation of Vectors, Matrices, and Arrays
MATLAB distinguishes column vectors from row vectors and, more significantly matrices from arrays. One distinguishes arrays from matrices in their arithmetic operations. Row vector => separate elements in rows by blanks or commas, and enclose the vector with square brackets, [ ]. >> a = [1 2 3] a =1 2 3 % [1 by 3 row vector]

Column vector => separate elements by semicolons and enclose the vector with square brackets, []. >> c = [4; 5; 6] c = 4 5 6 % [3 by 1 column vector]

Rectangular tabulations of elements constitute matrices and arrays. In indexing arrays: A(k, m) refers to Akm => element in kth row and mth column -

A11 A A = 21 A31 A41

A12 A13 A14 A22 A23 A24 A32 A33 A34 A42 A43 A44

Arrays/matrices can be constructed explicitly using [] notation with the ends of rows specified by semicolons ->> A = [2 3 4; 5 6 7; 8 9 10] A = 2 3 4 5 6 7 8 9 10 Both arrays and vectors can be constructed from previously defined vectors and arrays: >> z = [a 55 66] z = 1 2 3 55 66 >> a = [1 2]; b = [3 4]; c = [5;6]; >> d = [a; b] d =

1 3

2 4

12

>> e = [d c] e = 1 2 5 3 4 6 >> f = [[e e]; [a b a]] f = 1 2 5 1 3 4 6 3 1 2 3 4

2 4 1

5 6 2

The colon operator can be used to construct vectors: vector = lowest value : positive step : greatest value or vector = greatest value : negative step: lowest value >> x = 0.3*(0.0:.05:.15) x = 0 0.0150 0.0300 >> y = 10:-2:0 y = 10 8 6 4 2 0.0450 0

Built-in MATLAB functions can be used to create vectors and arrays: Check the function browser, fx, under Mathematics (particularly) - Arrays and Matrices Elementary Matrices and Arrays and Specialized Matrices - for useful/relevant MATLAB functions! For example note: linspace(x1, x2, N) generates a row vectors with N equal spaced points between x1 and x2. >> y = linspace(0, 1, 5) y = 0 0.2500 0.5000 0.7500 1.0000

To generate the corresponding column vector


>> y = linspace(0, 1, 5); zeros(m,n) ones(n) eye(n) rand(n) randm(n) randi(imax, [m,n]) repmat(A, m, n) >> rs = rand rs = 0.9853 => => => => => => m-by-n matrix of 0s. n-by-n matrix of 1s. n-by-n identity matrix. n-by-n matrix of uniformly distributed random numbers n-by-n matrix of normally distributed random numbers returns an m-by-n matrix of random integers uniformly between 1 and imax. => creates a large matrix B consisting of an m-by-n tiling of copies of A.

% Calling rand without attributes generates scalar random numbers

>> r = rand(3,1) r = 0.8147 0.9058 0.1270 >> r = rand(1,5) r = 0.9134 0.6324 >> eye(3)
ans = 1 0 0 1 0 0

0.0975

0.2785

0.5469

13

>> zeros(2) ans = 0 0 0 0 >> ones(2, 3) ans = 1 1 1 1 1 1

>> rand(3)
ans = 0.4860 0.8913 0.7621

% for details
0.4565 0.0185 0.8214 0.4447 0.6154 0.7919

>> A = randi(100, [8,8]) A = 65 6 98 97 21 61 100 73 38 6 79 42 79 42 44 75 69 31 50 27 47 88 22 44 57 2 65 94 80 77 33 69 >> A = [1 2; 3 4]; >> B = repmat(A, [3,3]) B = 1 2 1 2 3 4 3 4 1 2 1 2 3 4 3 4 1 2 1 2 3 4 3 4

22 84 63 14 21 61 63 38

58 46 5 3 32 2 39 69

10 4 62 61 2 2 20 59

6 37 64 72 70 9 46 45

1 3 1 3 1 3

2 4 2 4 2 4

Empty 0x0 matrix []: The operator [] can be employed to columns/rows from matrices:
>> C = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16] >> C(2,:) = [] C = 1 2 3 4 9 10 11 12 13 14 15 16 >> C(:,1) = [] C = 2 3 4 10 11 12 14 15 16

1.2.2 Functions to Manipulate Vectors, Matrices, and Arrays


Transpose of variable y is represented by y' (' symbol means the single quote). The transpose of row vector is a column vector. The transpose of column vector is a row vector.
>> y = 10:-2:0 y = 10 8 >> y ans = 10 8 6 4 2 0

14

6 4 2 0 >> c = [4; 5; 6]; >> c ans = 4 5 6

The transpose of the array An,m is Am,n >> A = [1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 >> A' ans = 1 4 7 2 5 8 3 6 9 >> w = 5:1:10 w = 5 6 >> dot(w,y) ans = 190 % some familiar vector functions 7 8 9 10

>> cross(w(1:3), y(1:3)) ans = -20 40 -20

% some familiar vector functions

Some more functions which can be applied to vectors:


length(x) sort(x) sum(x) min(x) [y, k]

returns the number of elements of x. sorts x in ascending order [sort in descending order, sort(x, descend)] sum of the elements of x. returns the smallest element of x. = min(x) (y is the smallest element of x and k is the index of y).
0.6068 0.4860 0.8913];

>> x = [0.9501 0.2311 length(x) ans = 5 >> size(x) ans = 1 5 >> sum(x) ans = 3.1653 >> sort (x) ans = 0.2311 0.4860 >> [v, k] = min(x) v = 0.2311 k = 1

0.6068

0.8913

0.9501

Apply these same functions to arrays: Essential property of such functions, applied now to matrices, is that thet they treat each column of a matrix as a distinct vector.
sort(A) sum(A) size(A) min(A) sum(A, 1) sum(A, 2)

sorts each column of A in ascending order. is a row vector whose elements are sums of columns of A. returns a vector containing the number of rows & columns of A. row vector containing the minimum of each column of A. returns a vector whose elements are the sum of the columns of A. returns a vector whose elements are the sums of the rows of A.

15

>> A = [9 897 44; 31 20 50; -75 -62 -98] A = 9 897 44 31 20 50 -75 -62 -98 >> sort (A) ans = -75 -62 -98 9 20 44 31 897 50 >> sum(A) ans = -35 >> min (A) ans = -75 >> size(A) ans = 3 3 855 -62 -4 -98

Additional Matrix Manipulation Functions:


reshape (A,m,n)

change size. Reshape returns the m-by-n matrix whose elements are tak en columnwise from X.

diag tril fliplr rot90

1.2.3 Extracting Elements via Subscripts and Colon Operators


Element/elements can be extracted from a previously defined vector. The relevant subscript/index is identified by an integer placed inside a pair of matched parentheses. NOTE that the element index starts at 1 and zero or negative indices are NOT supported!
>> y(2) ans = .25000 % NOTE: y defined previously

>> A = [2 3 4; 5 6 7; 8 9 10] A = 2 3 4 5 6 7 8 9 10 >> A(2, 1) ans = 5 >> A(3, 3) ans = 10

%Identifies the individual element -- 2nd row, 1st column % Identifies the individual elements -- 3rd row 3rd column

More sophisticated identifications can be performed: % elements from 1 to the end in steps of 2 >> y(1:2:end) ans = 0 0.5000 1.0000
>> y([5 4 2 3]) ans = 1.0000

% vector subscript 0.7500 0.2500

0.5000

16

>> A(1, :) ans = 2

% Identify first row


3 4

>> A(:, 1) ans = 2 5 8 >> A(2:3, 2:3) ans = 6 7 6 10 >> A(2:end, 2:end) ans = 6 7 9 10 >> A(:, 3)
ans = 4 7 10

% Identify first column

% NOTE: the use of the end format

% Identify the 3rd column

>> A(:, 3) = [-1; -2; -3] A = 2 3 -1 5 6 -2 8 9 -3

% Modify 3rd column

Sometimes one sees reference to A(:) where A is known to be a matrix. This operation transforms a two-dimensional matrix, A, into a corresponding one-dimensional vector, constructed in column major order:
>> A = [1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 >> A(:) 1 4 7 2 5 8 3 6 9

1.2.4 Arithmetic Operations


Scalar operations: add (+), subtract(-), multiply (*), divide (/), & exponentiation (^). How does MATLAB interpret, 5*3^3? Is it the cube of the product of 5 times 3 [no], or is it the product five times three cubed [yes]? What is the actual order of the operations? The order is set by rules of precedence. Precedence levels determine the order in which MATLAB, or any computer language, evaluates operators in multi-operator expressions. The precedence rules are ordered from the highest (1) to lowest precedence level (4):
1) 2) 3) 4) Parentheses (). Exponentiation (^). Multiplication (*) and division (/). Addition (+) and subtraction (-).

Within each precedence level, operators with equal precedence, say a multiplication and a division, are evaluated in order from left to right.

17

>> 2^4/10 ans = 1.6000 >> 5 + 4*9 ans = 41 >> -9 -8*2^2 ans = -41 >> 6 + 6/2*3 ans = 15 >> 6 + 6/(2*3) ans = 7 >> 2^2^2 >> [2^2^4 2^(2^4)] ans = 256 65536

Vector operations: Vector arithmetic operation function element by element . NOTE: presence of the periods!
x.*y x./y x.^2 = [x1*y1 + x2*y2 + ]. = [x1/y1 + x2/y2 + ]. = [x1^2 + x2^2 + ].

NOTE: without period these operations are very different!


>> x.*y ans = >> y./x ans = >> x.^2 ans = 0 0 0 0.0578 1.0818 0.0534 0.3034 0.8240 0.3682 0.3645 1.5432 0.2362 0.8913 1.1220 0.7944

>> x*y ERROR (explain below) ??? Err or using ==> *

Bulk of MATLAB's Intrinsic functions work with vector inputs


>> exp(x) ans = 2.5860 1.2600 >> sin(x) ans = 0.8135 0.2290 >> exp(-x).*sin(x) ans = 0.3146 0.1818 1.8346 0.5702 0.3108 1.6258 0.4671 0.2873 2.4383 0.7779 0.3190

Array/Matrix Operations:
Some (*, /, ^) arithmetic operations function differently for arrays and matrices. Matrix operations are predicated on the normal rules of linear algebra. However, all arithmetic array operations work on an element-by-element basis and thus require same-sized parent arrays. >> A = [1 2; 3 4]; B = 3*ones(2) A = 1 2 3 4 B = 3 3 3 3

18

>> A + B ans = 4 6 >> A - B ans = -2 0

5 7

-1 1

Array multiplication: C(i, j) = A(i, j).* B(i, j) >> A.*B ans = 3 9 6 12

NOTE the presence of the period before the asterisk.


Array division: >> A./B
ans = 3.3333 1.0000 0.66667 1.3333

C(i, j) = A(i, j)./ B(i, j)

NOTE the presence of the period before the slash.


Matrix Operations: A B produce the same result as array additions/subtractions, and are valid only if A & B are the same size. However, the product A*B for matrices is valid if the number of columns of A equals the number of rows of B. Thus matrix multiplication does not require A and B be same size! Matrix multiplication is different from elementby-element array multiplication. Observe that

A = n -by-m sized matrix, B = m-by-k sized matrix C A*B C = n-by-k sized array Cij = ith row of A i jth column of B

C ij

k=1 Aik iBkj


k=m

>> E = [1 2 3; 5 7 9]
E = 1 5 G = 6 21 19 H = 105 348 2 7 11 -1 77 240 741 3 9

>> G = [6 11; 21 -1; 19 77]

>> H = E*G

Matrix multiplication spelled out

19

H H(i, j) H(1, 1)

= E * G = sum(E(i, :)*G(:, j)) = E(1, :) * G(:, 1) = [1 2 3]*[6 21 19] = 105

Matrix multiplication is not commutative Bi A A iB. >> G*E ans = 61 16 404 % G*E E*G 89 35 577 117 54 750

In MATLAB left or backslash division used solely to solve systems of linear equation, where A is an nxn sized matrix, whose elements are all known, b is a nx1 vector whose components are known but x is nx1 vector whose elements are unknown A*x = b

x & b are column vectors x = A\b (left division)


System of Linear Equations: 3x1 +2x 2 - x 3 = 10 -x1 +3x 2 + 2x 3 = +x1 -x 2 5 + x 3 = -1

x1 +3 2 -1 10 -1 3 2 ,b 5 , x x A 2 x3 +1 -1 -1 -1
A*x 1 =b

+3 2 = -1 3 +1 -1

x1 10 * x = 5 2 2 -1 x 3 -1
= A\b

Solve A*x = b in MATLAB by left matrix division x

>> A = [3 2 1; -1 3 2; 1 -1 -1] A = 3 2 1 -1 3 2 1 -1 -1 >> b = [10;5;-1] b = 10 5 -1 >> x = A\b x = 2.0000 1.0000 2.0000 >> ck = A*x b ck = 1.0e-014 * 0 % Checks OK => differences ~ 102eps

20

-0.1776 0.0222

1.2.5 Relational Operators


== ~= < > <= >= equal not equal less than greater than less than or equal greater than or equal

Remember that a single = denotes assignment! Don't test for equality, using X =Y, which sets X equals the value of Y. Result of relational operation -1 if relation is TRUE 0 if relation is FALSE Scalars: >> 3 > 2 ans = 1 >> 2 > 3 ans = 0 >> -4 <= -3 ans = 1 >> 1 < 1 ans = 0 >> 1 <= 1 ans = 1 >> 2 ~= 2 ans = 0 >> 3 == 3 ans = 1 >> 0 < 0.5 < 1 ans = 0

SHOULD be 1, but what happened! Culprit is operator precedence remember it is from left to right. What happens was first 0 < 0.5 returns 1 and then second tests 1 < 1 which is false or 0. Arrays/Matrices:
>> B = 2.0*ones(3); >> A = [1 2 3; 4 5 6; 7 8 9]
2 5 8 3 6 9

A = 1 4 7

>> A == B ans = 0 0 0

1 0 0

0 0 0

21

>> A > B ans = 0 1 1

0 1 1

1 1 1

A number of relational functions: isequal, isempty, isfinite, isnan, etc >> isequal(A, B) ans = 0 >> A = [1 2 3; 5 6 7] >> A == 7 ans = 0 0 0 0 0 1

>> isequal (A, 7) ans = 0

1.2.6 Logical Operators


& | ~ logical and logical or logical not

Logical functions: all any TRUE if all elements are nonzero (dont have to be 1s). TRUE if any element are nonzero (dont have to be 1s).

As with relational operators, logical operations produce matrices of 0s & 1s.

Vectors:
>> x = [-1 1 1]; y = [1 2 -3]; >> x > 0 ans = 0 >> y > 0 ans = 1 1 1 1 0 0 % OR 1

>> x >0 & y > 0 ans = 0 1 >> x > 0 | y > 0 ans = 1 1 >> any(x) ans = 1 >> all(y) ans = 1

Matrices:
all(X)operates on the columns of X, returning a row vector of 1's and 0's.

22

Similarly, any(X) operates on the columns of X, returning a row vector of 1's and 0's.
>> B = [9 8 7; 6 5 0; 0 0 1] B = 9 8 7 6 5 0 0 0 1 >> all(B) ans = 0 >> any(B) ans = 1 0 1 0 1

To test equality of matrices using all, use nested functions OR use isequal >> C = [19 8 7; 6 5 0; -3 0 1] C = 19 8 7 6 5 0 -3 0 1 >> all( all( C == B) ) ans = 0 >> any( any( C == B) ) ans = 1 >> isequal(B, C) ans = 0

Logical function find:


A useful function is find, which returns the indices of the nonzero elements of a matrix. >> x = [-3 1 0 -inf 0] >> find(x == -inf) ans = 4 >> f = find(x) f = 1 2 >> x(f) ans = -3 1 4 -Inf

>> x(find(x < 0)) ans = -3 -Inf >> A = [4 2 16; 12 4 3]


A = 4 12 2 4 16 3

>> B = [12 3 1; 10 -1 7] B =12 3 1 10 -1 7 >> A < B


ans = 1 1 0

23

Can use find with matrix indices:


>> [r, c] = find(A < B); >> [r c] % row & column indices
ans = 1 1 2 1 2 3

Say you want to set these elements of A to 9


>> A([r c]) = -9; >> A A = -9 -9 16 -9 4 3 NOTE: find applied to matrix A, the resulting index vector corresponds to A as a vector of columns stacked one on another, as in (A(:)).

1.3 FUNCTIONS
1.3.1 M-Files
M-file is a text file, entitled ZZZ.m, created with an .m extension and it contains a sequence of MATLAB commands. An m-file is equivalent to typing all the commands stored in the file. Why use: It is easier to edit a file of commands rather than retyping a long list of commands. Makes a permanent record of your commands. Creates procedures that can be reused at a later date. Scripts: A script is simply a list of MATLAB commands. Variables created in script execution remain in the Workspace. Scripts overwrite preexisting variables in the Workspace. CAUTION when using scripts you can make unintended modifications of workspace variables. Note the script rainfall.m below. % contents of rainfall.m rain = [3.47 1.58 4.75 0.17 2.19 1.90 3.82 3.97 0.93 2.44 2.22 3.23]; rain_sort = sort(rain) rain_mean = mean(rain) rain_med = median(rain) rain_std = std(rain) >> rainfall rain_sort= 0.17 0.93 1.58 1.90 2.19 2.22 2.44 3.23 3.47 3.82 3.97 4.75 rain_mean= 2.5558 rain_med = 2.3300 rain_std = 1.3376 >> whos % After running rainfall.m in Name Size Bytes ans 1x12 96 rain 1x12 96 rain_mean 1x1 8 the Command Window Class double double double

24

rain_med rain_sort rain_std

1x1 1x12 1x1

8 96 8

double double double

. Functions: - preferred approach Variables created in a function exist only in the local function space. Functions can accept input arguments. After execution, the only function variables which remain in the Workspace are the function output variables. Functions can usually exchange data with the workspace via either input/output arguments. Function m-files must start with the key word function -function [out_arg1, out_arg2, ] = name_of_function(in_arg1,in_arg2,) 1) The first line of a function must begins with the KEYWORD function a) The word function is followed by the output argument (single) OR output arguments (plural) in square brackets [ ], where the output variables are separated by commas. b) The square bracket is then followed by the assignment symbol, =. c) The assignment symbol is then followed the user-defined function name, which should match the name of the file. The names of functions follow the same naming conventions as do variable names. d) The function name is followed by a comma separated list of input argument[s] placed inside parentheses, (). 2) It is suggested that a comment section, listing input/output arguments and a short description of the functions purpose, be placed immediately following the function line. These comments, immediately following the 1st line, are displayed on the command window, if one types >> help function_name. This is a useful way to inform the function user of functions input/output arguments. 3) The core of the procedure follows the comment section. 4) The function terminates when the last line is executed OR when the return statement is encountered. A simple example of a user-constructed function is the following function [mean, standard_dev] = stats(x)
%function [mean, standard_dev] = stats(x) % INPUT: % x vector % OUTPUT: % mean scalar % standard_dev scalar

n xb standard_dev mean

= = = =

length(x); sum(x)/n; sqrt(sum((x - xb).^2)/(n - 1)); xb;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Examples of calling sequences are the following: >> [r, a, z] = motion(x, y, t); >> [r, p, q] = motion(x, y, [0:1:100]) >> [a, b, c] = motion(0.5, 12.0, 66.0);

1.3.2 Anonymous Functions 25

Anonymous functions are an elegant way to create short user-defined functions without cluttering file directories with a large number of short files! You create anonymous functions in the command window or in a parent m-file by simply typing the following f1 = @(argument_list) expression From the left: f1 = @ (x,y, ) expression

name or handle of the function, assignment operator, function handle symbol, a comma separated list of input arguments, a single MATLAB expression, or command.

>> f1 = @(x) x^2 1; >> f1(5) ans = 24

If you want to input vectors, more care is needed in formulation!


>> f1( [4 5 6]) ??? Error using ==> mpower Matrix must be square. % Another unclear error message!

Here the function must be created in vector format, employing the period notation,
>> f1 = @(x) (x.^2 1); >> f1( [ 4 5 6]) ans = 15 24 35

Anonymous functions can depend on multiple input variables:


>> g = @(u, v) u.^2 + v.^2;

1.3.3 Passing Functions as Arguments to other Functions


You need to be able to pass names of functions to other functions in order to perform a variety of tasks - solve integrations and ordinary differential equations, etc. In other words, functions must be able to call other functions. Obviously MATLAB must discriminate somehow between the names of functions and the names of variables. A function handle (@) provides the preferred approach on how MATLAB procedures can call other functions. Let us employ the MATLAB intrinsic function, ezplot, as an example of a function calling a second function. The function, ezplot, graphs a function, supplied as input, over a default domain of to +; the only input required by ezplot is the name of the function to be plotted.

a) Calling Intrinsic MATLAB Functions


>> ezplot(sin) ??? Error using ==> sin Not enough input arguments.

<= opaque error message!

What happened here was that the input function was improperly called, but if one employs the symbol @ ->> ezplot(@sin) % it works

The preferred way to properly call a built-in function is to use a function handle.

26

b) Calling User-Created m-file Functions Similarly, we must employ a function handle to access an m-file function we have created. If we attempt to plot our own m-file function, without a function handle, we get a different error message
>> ezplot(f2) ??? Input argument "x" is undefined.

However, we can successfully plot the user created m-file function with a function handle >> ezplot(@f2) % works

c) Anonymous Functions How does one pass an anonymous function to ezplot? Prior to our call to ezplot, we create an anonymous function, g, say the following >> g = @(x) cos(x.^2) g = @(x)cos(x.^2)

Observe that the inspection of the Workspace shows that a function handle, named g, exists already. Thus you do not need to create, and must not create, a function handle again >> ezplot(g) % works

1.4 FLOW CONTROL


1.4.1 if-end Expressions
Works best with scalars or arrays/matrices with certain logical functions (all, any)
if logical_condition_test_1 statements_1 end % Simplest form

If logical_condition_test_1 is nonzero above, statements_1 are performed if logical_condition_test_2 statements_2 else statements_3 end

If logical_condition_test_2 is nonzero, statements_2 are performed. However, if logical _condition_test_2 is zero, statements_3 are performed. More complicated tests, such as below, can be created.
if logical_condition_test_4 statements_4 elseif logical_condition_test_5 statements_5 else statements_6 end

Logical condition tests usually are variables coupled by relational operators (x < 2.0) or logical functions, all(x < 0).

27

Simple if constructs can be written on a single line if x >= 0.0, y = sqrt(x), end % Function example: function [mean, standard_dev] = stats(x) [r, c] = size(x); % An error occurs if x is an array % Input of either a row or column vector is acceptable if r == 1 | c == 1; % c == 1 x => column vector % r == 1 x => row vector n = length(x); xb = sum(x)/n; standard_dev = sqrt(sum((x - xb).^2)/(n - 1)); mean = xb; else disp('You input an array & not a vector'); end

Be careful applying if A . . .end with arrays, A, if-end acts the SAME if all(all(A))! If you are attempting to test individual elements of vectors or arrays DO NOT use the if-else-end construct. USE find(A)!

1.4.2 For Loops


Used when you know ahead of time the number of iterations needed. for variable = expression statements end expression of the form => lower:step:upper NOTE: step can be a negative NOTE: if step is omitted, it is assumed to be 1. % Sum of first 25 terms of series 1/k >> s = 0.0; % NOTE: must initialize s to 0.0 >> for k = 1:25; s = s + 1.0/k; end >> s s = 3.8160 NOTE: loop expression can be defined in square bracket notation >> for x = [pi/6. pi/4, pi/3], disp([x, sin(x)] ), end 0.5236 0.5000 0.7854 0.7071 1.0472 0.8660

1.4.3 While Loops


Used when know the number of iterations is not known prior to execution.
while logical_expression statements end

28

NOTE: statements executed as long as logical_expression is true function result = newton_sq_root(a) % function result = newton_sq_root(a) % Calculates a square of a number via Newton's method % INPUT: a % OUTPUT: result old = realmax; % dummy start value new = a/2; % Choice arbitrary while (abs((new - old)/new) > eps | abs(new old) > eps) old = new; new = (old + a/old)/2; end result = new; >>newton_sq_root(10000.0) ans = 100 You can employ while loops with the logical expression always set to true (1) but exit the loop with a break statement. function result = newton_sq_rootB(a) % function resultB = newton_sq_rootB(a) % Calculates a square of a number via Newton's method % INPUT: a % OUTPUT: result old = realmax; % dummy start value new = a/2; while 1 % infinite loop old = new; new = (old + a/old)/2; % NOTE: reversed the criterion from above if abs((new - old)/new) <= eps; break; end end result = new; >> newton_sq_rootB(10000.0) ans = 100

1.5 PLOTS
If x and y are vectors of the same length, a simple plot can be created quickly in the command window. Here the use of the string, ro, means that the curve is plotted symbols as red circles >> x = 0.0:1.0e-02:2*pi; y = sin(x).*exp(-x); >> plot(x, y, ro);

29

0.35 0.3 0.25 0.2 0.15 0.1 0.05 0 -0.05

1.5.1 Structure of a MATLAB Plot

By default MATLAB employs colors to discriminate data sets in plots. The sequence of the colors of the different-colored line plots can be changed by the user. Also text can be added to your figure. The easiest way to modify a plot is to activate the Plot Tool icon (the last icon on the right the white square with double-lined border).

1.5.2 Interactive Plotting


This is the preferred approach in creating a plot; it minimizes the number functions you must remember! Create some vectors in the command window:

30

>> x= 0:0.05:2*pi; >> y = sin(x).*exp(-x);

Click once on either vector in the Workspace menu; do not double click. To the right of the middle of the Workspace menu bar (next to the delete button) is the graph icon (white rectangle with blue curve). On the right of this icon, activate the pull-down plot menu by clicking & holding-down the oblong vertical button - release when you have high-lighted the more plots button, which opens the plot catalog.

Then in the Plotted Variables tab type x,y while the 1st plot (single sinusoid) is highlighted. Double clicking on the high lighted plot panel produces the plot below --

31

Now in window labeled Figure 1, on the icon the Show Plot Tools (2nd row, last icon on right --- that is the white square with double borders). Now the window below appears --

Now you can change line thickness, style and color using the dialog box below the plot Figure. If relevant item does not appear, then double click on the curve. Now you can label the appropriate axes!

32

Now plot a curve in three dimensions.


>> >> >> >> t y x z = = = = 0:0.05:10*pi; sin(t).*exp(-t/10); cos(t).*exp(-t/10); t/10;

Highlight variable t in the Workspace. In the middle of the menu bar on the Workspace menu bar (next to the delete button) is the graph icon (white rectangle with blue curve). On the right of this icon, activate the pull-down plot menu by clicking & holding-down the oblong vertical button - release when you have high-lighted the more plots button, which opens the plot catalog. In the Plotted Variables tab, type x, y, z. Then double click on plot3 panel icon. The Figure below results.

MATLAB graphics highly customizable! I modified the above plot: Thickened the line. Colored the curve blue.

33

Increased the font size. Labeled the axes. Created a title and colored red.

1.5.3 Creation of Simple Plots via Command Line


MATLAB possesses powerful graphics capabilities. Start searching documentation with: Help tab => Product Help => User Guides => Graphics => OR fx => MATLAB => Graphics => Basic Plots and Graphs Basic Plotting Commands => plot, plot3, loglog, semiplogx, semilogy, plotyy >> >> >> >> x = [1.5 2.2 y = [2.3 3.9 plot(x, y); plot(y); 3.1 4.6 5.7 6.3 9.4]; 4.3 7.2 4.5 3.8 1.1]; % data points joined in sequence (See below) % y values plotted against their indices

Other 2D plots of interest: loglog log-scaled axes semilogx log-scaled x axis semilogy log-scaled y axis bar bar graph hist histogram Two useful graphics commands grid add major lines to current axes zoom zoom in & out on 2D plots

1.5.4 Creating Multiple Curves in a Single Plot Frame


Can be constructed from Plot Tools Palette Figure Palette 2D Axes Click on square made of 4 smaller squares Add Data tab Plot Type/ X Data Source/ Y data Source Figure Palette 2D Axes Click on square made of 4 smaller squares Add Data tab OR use command-line subplot!

34

1.5.5 Plots of Functions


One can employ ezplot to create plots of functions: => ezplot(@f) plots the expression f = f(x) over the default domain: -2 < x < 2. => ezplot(@f,[min,max]) plots f = f(x) over the domain: min < x < max. >> ezplot(@sin);
sin 1

0.5

-0.5

-1

-6

-4

-2

0 x

>> f = inline('cos(x).*exp(-x)'); >> ezplot(f)

35

cos(x) exp(-x)

60

40

20

-20

-40 -6 -5 -4 -3 -2 -1 x 0 1 2 3 4

1.5.6 How to Save a Figure


File Generate m-file Automatically create an m-file to reproduce figure! NOTE: this function still requires input vectors!

File tab Save As a file name_of_figure..fig MATLAB format ( you can load this figure via Workspace icon) name_of_figure2.emf for insert into Word name_of_figure3.jpg for insert into Word
To insert the figure in a Word document: [Figure 1] File Save Save as plot3.jpg [Saved in jpg format.] [Word] Insert Picture From File {plot3d.jpg} Tried other file formats: emf, eps, pdf, & tif Storage varies from plot.eps (5.3 M) to plot.pdf (13 KB).

4) Tips For Beginners (Dorfman 2007; Driscoll 2009)


Employ the up-arrow key to access previous commands. Type specific characters first and only matching commands are displayed. To interrupt a computation, type Ctrl-C in the command window. MATLAB possesses excellent debugging. Employ them, running your code step-by-step to identify errors. Modularize code into functional components, especially input, output, and core algorithm. Effectively use The Help and Debugging tools. Use the M-Lint code checker to identify problems in your code.

36

Use the Profiler to find the slowest steps in your code. Create output functions which create professional quality figures. Employ anonymous functions wherever possible!

1.7 References
Burden, R. L., and Faires, J. D. Numerical Analysis, 7th Ed., 2001, (Brooks/Cole, Pacific Grove CA). Dorfman, J. H. Introduction to MATLAB Programming, 2007 (Decagon: Berkeley, CA). Driscoll, T. A. Learning MATLAB, 2009 (SIAM: Philadelphia, PA). Hahn, B. D. Essential MATLAB for Scientists and Engineers, 2nd Ed, 2002 (Butterworth-Heinmann, Oxford, UK) Hanselman D., and Littlefield, B. Mastering MATLAB 6, 2001 (Prentice Hall: Upper Saddle River, NJ). Higham, D. J., and Higham, N. J., MATLAB Guide, 2nd Ed.,2005 (SIAM: Philadelphia, PA). Hunt, B. R. et al, A Guide to MATLAB for Beginners and Experienced Users, 2001 (Cambridge University Press: Cambridge, UK). Kelley, C. T., Solving Nonlinear Equations with Newton's Method, 2003 (SIAM: Philadelphia). Pratap, R., Getting Started with MATLAB, A Quick Introduction for Scientists and Engineers, 2002 (Oxford University: Oxford, UK).

37

You might also like