1.
1 MATLAB ESSENTIALS PHYS100<br /> <br />1.1 BASICS<br />1.1.1 Start and Termination of a MATLAB Session2<br />1.1.2 Desktop Environment2<br />1.1.3 Saving Variables and Command Window Session & Variables8<br />1.1.4Floating-Point (Real) Numbers9<br />1.1.5Additional MATLAB Data Classes10<br />1.2 MATRICES AND VECTORS 1.2.1 Creation of Vectors12<br />1.2.2 Functions to Manipulate Vectors, Matrices, and Arrays15<br />1.2.3 Extract Elements via Subscripts and Colon Operators 16<br />1.2.4Arithmetic Operators 18<br />1.2.5 Relational Operators 21<br />1.2.6Logical Operators 23<br />1.3 FUNCTIONS <br />1.3.1 M Files 25<br />1.3.2 Anonymous Functions 26<br />1.3.3 Passing Functions as Arguments to other Functions27<br />1.4 FLOW CONTROL <br />1.4.1 if-end Expressions 28<br />1.4.2 for Loops29<br />1.4.3 while Loops29 <br />1.5 PLOTS<br />1.5.1 Structure of a MATLAB Plot 31<br />1.5.2 Interactive Plotting31<br />1.5.3 Creation of Simple Plots via Command Line35<br />1.5.4 Generation of Multiple Curves in a Single Plot Frame 35<br />1.5.5 Plots of Functions 36<br />1.5.6 How to Save a Figure 36<br />1.6 TIPS FOR BEGINNERS37<br />1.7 REFERENCES37<br />1 MATLAB BASICS <br />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++. <br />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. <br />
How to Start & Terminate MATLAB Sessions:
Start MATLAB by double clicking on the icon labeled MATLAB in the All Programs menu. <br />Terminate a MATLAB session in any of three ways: <br />type Ctrl q simultaneously on the keyboard, OR, <br />click Exit MATLAB, the final entry of the File menu, OR, <br />type quit or exit at the command prompt (>>) in the Command Window. <br />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. <br />Desktop Environment – see figure on page 4:<br />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.<br />Command Window: <= Large panel in the middle of the figure. <br />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:<br />>> 6*7 <br /> <br />ans = <br />42 <br />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, <br />>> format compact<br />>> 6*7<br />ans =<br /> 42<br />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 =. <br />One can place multiple commands on a single line by separating them by commas –<br />>> cos(0.0), cos(pi/4.0)<br />ans = 1<br />ans = 0.7071<br />Employ the = symbol to assign values to variables - <br />>> x = exp(2), y = cos(0.25*pi), z = x + y<br />x = 7.3891<br />y = 0.7071<br />z = 8.0962<br />Variable Names. All variable names must:<br />Start with a letter.<br />Consist of letters (a-z, A-Z), digits (0-9), and underscore (_), <br />MATLAB distinguishes UPPER & lower case letters. <br />Can contain a maximum of 63 characters. <br />Cannot contain blanks. <br />Some built-In MATLAB variables are:<br />pi3.14159265358979<br />i, j(-1.0)0.5<br />Inf result of n/0, where n is any non-zero real number<br />NaNNot a number, created by 0/0 or 0*Inf, <br />MATLAB has reserved keywords which cannot be used as variable names. These keywords can be identified by typing -- <br />>> iskeyword <br />break <br />case<br />catch<br />classdef <br />continue<br />else<br />elseif<br /> end<br />for<br />function<br />global<br />if<br />otherwise<br />parfor <br />persistent<br />return<br />spmd<br />switch<br />try<br />while<br />MATLAB displays variables in floating point notation:<br />3.782x1011 is represented as 3.782e+11.<br />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. <br />NOTE: the following format is legal but do not use – 3.56*10^9, specify a number as 3.59e9!<br />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.<br />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.<br />Inserting comments – use %. All text on a line following the % symbol is ignored by MATLAB.<br />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.<br />Workspace Browser: <= small panel on the upper right.<br />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. <br />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. <br />You can use the Variable Editor in the Workspace panel to inspect the contents of arrays. <br />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.<br /> <br />Command History: <= small panel on the lower right. <br />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.<br />Editor/Debugger: [Not shown in the Desktop Environment figure.] <br />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. <br />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. <br />Mathworks offers you several options for accessing help while running MATLAB.<br />Help Browser: To open the help browser: <br />click on the Help tab on the top toolbar, OR, <br /> click the help button blue-circled ? symbol (immediately below the Help tab), OR, <br /> type helpbrowser in the Command Window.<br />NOTE that the tabs in the Help Window Navigator (shown below) provide different ways to search for information: contents, index, or search. <br />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 –<br />Mathworks third option for accessing help while running MATLAB is type <br />>> help name_of_function <br />in the Command Window environment. If you do not know/remember the name of the function you can type –<br />>> lookfor name_of_function <br />Finally, you can access MathWorks website from MATLAB under the Help tab => Web Resources => The MathWorks Web Site. <br />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):<br />MATLAB@ 7 Getting Started Guide (getstart.pdf)(260 pg.)<br />MATLAB@ 7 Desktop Tools and Development Environment (matlab_env.pdf)(957 pg.)<br />MATLAB@ 7 Mathematics (math.pdf)(443 pg.)<br />MATLAB@ 7 Programming Fundamentals (matlab_prog.pdf)(837 pg.)<br />MATLAB@ 7 Programming Tips (programming_tips.pdf)(65 pg.)<br />MATLAB@ 7 Object-Oriented Programming (matlab_oop.pdf)(437 pg.)<br />MATLAB@ 7 Data Analysis (data_analysis.pdf)(216 pg.)<br />MATLAB@ 7 Graphics (graphg.pdf)(671 pg.)<br />MATLAB@ 7 3D Visualization (visualize.pdf)(212 pg.)<br />MATLAB@ 7 Function Reference: A-E (refbook.pdf)(1378 pg.)<br />MATLAB@ 7 Function Reference: F-O (refbook2.pdf)(1732 pg.)<br />MATLAB@ 7 Function Reference: P-Z (refbook3.pdf)(1802 pg.)<br />An Additional MATLAB Resource:<br />Electronic Resources at http:/libraries.claremont.edu<br />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). <br />1.1.3) Saving a Command-Window Sessions & Variables:<br />First you can save all the command text input/output in the command window to a file via the diary command.<br />Second you can save the variables you have created during a MATLAB session to a separate file via the save command.<br />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'). Don’t 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<br />>> diary<br />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 <br />>> diary off<br />To turn on diary storage type<br />>> diary on <br />Hint: appropriate use of the diary command is an excellent way to create home works and tests.<br />To save all the workspace variables for later use, at the end of a session, type in the Command Window –<br />>> save name_of_file<br />All the variables are stored in a binary (machine-readable not text readable) file called name_of_file.mat. If you type<br />>> save<br />All the variables are store in a file with the default name, matlab.mat. If you type at the prompt <br />>> save name_of_file_2 x y z <br />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 <br />>> load name_of_file<br />You do not need to use the extension .mat -- .mat is assumed. <br />1.1.5 Floating-Point (REAL) Numbers<br />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.<br />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 –<br />>> eps<br />ans = 2.2204e-016<br /> 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 <br />>> realmax(‘double’)<br /> ans = 1.797693134862316e+308<br />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 -<br />> >> 10.0/0.0, -10.0/0.0<br />ans = Inf<br />ans = -Inf<br />Please observe that overflows do not halt calculations. Although numbers can possess up to 308 decimal digits, BUT only 16 decimal digits are significant! For example, <br />>> realmax(‘double’)<br />ans = 1.797693134862316e+308<br />>> realmax (‘double’)+ 1.0e291<br />ans = 1.797693134862316e+308<br />>> realmax(‘double’) + 9.0e291<br />ans = 1.797693134862316e+308<br />>> realmax(‘double’) + 1.0e292<br />ans = Inf<br />The behavior of small numbers is different. There exists a parameter called realmin, <br />>> realmin(‘double’)<br />ans = 2.225073858507201e-308<br /> <br />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.<br />Complex Numbers:<br />Complex numbers can be created simply from the function complex -<br />>> z = complex(rand(4,1), rand(4,1))<br />z = 0.7094 + 0.6551i<br /> 0.7547 + 0.1626i<br /> 0.2760 + 0.1190i<br /> 0.6797 + 0.4984i<br />>> size(z)<br />ans =4 1<br />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 -<br />>> real(z)'<br />ans = 0.7094 0.7547 0.2760 0.6797<br />>> imag(z)'<br />ans = 0.6551 0.1626 0.1190 0.4984<br />>> ctranspose(z)<br />ans =0.7094 - 0.6551i 0.7547 - 0.1626i 0.2760 - 0.1190i 0.6797 - 0.4984i<br />>> conj(z)<br />ans =0.7094 - 0.6551i<br /> 0.7547 - 0.1626i<br /> 0.2760 - 0.1190i<br /> 0.6797 - 0.4984i<br />>> class(z)<br />ans = double<br />Note that complex numbers do NOT constitute a distinct data class. Such numbers by default store their real and imaginary components in double precision. <br />1.1.5 Additional MATLAB Data Classes<br />MATLAB employs other classes of variables, beyond the 64-bit class double:<br />(e.g. [p. 40] Higham & Highhan 2005)<br />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 employment of single precision does not lead to a significant speed advantage, it use in coding is not recommended.<br />>> realmax('single')<br />ans = 3.4028e+038<br />>> realmin('single')<br />ans = 1.1755e-038<br />>> eps('single')<br />ans = 1.1921e-007<br />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.<br />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.<br /> >> [intmin('int8') intmax('int8')]<br />ans = -128 127<br />>> [intmin('uint8') intmax('uint8')]<br />ans = 0 255<br />>> [intmin('int32') intmax('int32')]<br />ans = -2147483648 2147483647<br />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 - <br />>> [int8(-130) int8(130)]<br />ans = -128 127<br /> <br />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.<br /> >> s = 'name of city'<br />s = name of city<br />>> char([67 80 81])<br />ans = CPQ<br />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, {}.<br />>> B = { [1 2 3], 'data', int8(66) }<br />B = [1x3 double] 'data' [66]<br />>> class(B)<br />ans = cell<br />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 -<br />>> S.name = 'john smith';<br />>> S.score= 89;<br />>> S.grade= 'B+';<br />>> class(S)<br />ans = struct<br />>> S<br />S = <br />name: 'john smith'<br />score: 89<br />grade: 'B+'<br />1.2 MATRICES, ARRAYS, AND VECTORS<br />1.2.1 Creation of Vectors, Matrices, and Arrays<br />MATLAB distinguishes column vectors from row vectors and, more significantly matrices from arrays. One distinguishes arrays from matrices in their arithmetic operations. <br />Row vector => separate elements in rows by blanks or commas, and enclose the vector with square brackets, [ ]. <br /> <br />>> a = [1 2 3] % [1 by 3 row vector]<br />a =12 3<br />Column vector => separate elements by semicolons and enclose the vector with square brackets, [].<br />>> c = [4; 5; 6] % [3 by 1 column vector]<br />c =4<br />5<br />6<br />Rectangular tabulations of elements constitute matrices and arrays. In indexing arrays: A(k, m) refers to Akm => element in kth row and mth column -<br />Arrays/matrices can be constructed explicitly using [] notation with the ends of rows specified by semicolons --<br />>> A = [2 3 4; 5 6 7; 8 9 10]<br />A = 2 3 4<br /> 5 6 7<br /> 8 9 10<br />Both arrays and vectors can be constructed from previously defined vectors and arrays:<br />>> z = [a 55 66]<br />z = 1 2 3 55 66<br />>> a = [1 2]; b = [3 4]; c = [5;6]; <br />>> d = [a; b]<br />d =<br /> 1 2<br /> 3 4<br />>> e = [d c]<br />e =<br /> 1 2 5<br /> 3 4 6<br />>> f = [[e e]; [a b a]]<br />f =<br /> 1 2 5 1 2 5<br /> 3 4 6 3 4 6<br /> 1 2 3 4 1 2<br />The colon operator can be used to construct vectors: <br />vector = lowest value : positive step : greatest value or vector = greatest value : negative step: lowest value -<br />>> x = 0.3*(0.0:.05:.15)<br />x = 0 0.0150 0.0300 0.0450<br />>> y = 10:-2:0 <br />y = 10 8 6 4 2 0<br /> Built-in MATLAB functions can be used to create vectors and arrays: <br />Check the function browser, fx, under Mathematics (particularly) - Arrays and Matrices - <br />Elementary Matrices and Arrays and Specialized Matrices - for useful/relevant MATLAB functions! <br /> <br />For example note:<br />linspace(x1, x2, N) generates a row vectors with N equal spaced points between x1 and x2.<br />>> y = linspace(0, 1, 5)<br />y = 0 0.2500 0.5000 0.7500 1.0000<br />To generate the corresponding column vector –<br />>> y = linspace(0, 1, 5)’;<br />zeros(m,n) => m-by-n matrix of 0s.<br />ones(n) => n-by-n matrix of 1s.<br />eye(n) => n-by-n identity matrix. <br />rand(n) => n-by-n matrix of uniformly distributed random numbers<br />randm(n) => n-by-n matrix of normally distributed random numbers<br />randi(imax, [m,n]) => returns an m-by-n matrix of random integers uniformly<br /> between 1 and imax.<br />repmat(A, m, n) => creates a large matrix B consisting of an m-by-n<br /> tiling of copies of A.<br />>> rs = rand % Calling rand without attributes generates scalar random numbers<br />rs = 0.9853<br />>> r = rand(3,1)<br />r =<br /> 0.8147<br /> 0.9058<br /> 0.1270<br />>> r = rand(1,5)<br />r = 0.9134 0.6324 0.0975 0.2785 0.5469<br />>> eye(3)<br />ans = 1 0 0<br /> 0 1 0<br /> 0 0 1<br />>> zeros(2) <br />ans = 0 0 <br /> 0 0<br />>> ones(2, 3) <br />ans = 1 1 1<br /> 1 1 1<br />>> rand(3)% for details <br />ans = 0.4860 0.4565 0.4447<br /> 0.8913 0.0185 0.6154<br /> 0.7621 0.8214 0.7919<br />>> A = randi(100, [8,8])<br />A =65 6 98 97 22 58 10 6<br /> 21 61 100 73 84 46 4 37<br /> 38 6 79 42 63 5 62 64<br /> 79 42 44 75 14 3 61 72<br /> 69 31 50 27 21 32 2 70<br /> 47 88 22 44 61 2 2 9<br /> 57 2 65 94 63 39 20 46<br /> 80 77 33 69 38 69 59 45<br />>> A = [1 2; 3 4];<br />>> B = repmat(A, [3,3])<br />B =<br /> 1 2 1 2 1 2<br /> 3 4 3 4 3 4<br /> 1 2 1 2 1 2<br /> 3 4 3 4 3 4<br /> 1 2 1 2 1 2<br /> 3 4 3 4 3 4<br />Empty 0x0 matrix – []:<br />The operator [] can be employed to columns/rows from matrices: <br />>> C = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16] <br />>> C(2,:) = []<br />C =1 2 3 4<br /> 9 10 11 12<br /> 13 14 15 16<br />>> C(:,1) = []<br />C =2 3 4<br /> 10 11 12<br /> 14 15 16<br />1.2.2 Functions to Manipulate Vectors, Matrices, and Arrays<br />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. <br />>> y = 10:-2:0 <br /> y = 10 8 6 4 2 0<br />>> y’ <br />ans =<br />10<br /> 8<br /> 6<br />4<br />2<br />0 <br />>> c = [4; 5; 6]; <br />>> c’<br />ans = 4 5 6<br />The transpose of the array An,m is Am,n - <br />>> A = [1 2 3; 4 5 6; 7 8 9]<br />A =<br /> 1 2 3<br /> 4 5 6<br /> 7 8 9<br />>> A' <br />ans =<br /> 1 4 7<br /> 2 5 8<br /> 3 6 9<br />>> w = 5:1:10 % some familiar vector functions <br />w = 5 6 7 8 9 10<br />>> dot(w,y)<br />ans = 190<br />>> cross(w(1:3), y(1:3)) % some familiar vector functions<br />ans = -20 40 -20<br />Some more functions which can be applied to vectors: <br />length(x)returns the number of elements of x.<br />sort(x)sorts x in ascending order [sort in descending order, sort(x, ‘descend’)]<br />sum(x)sum of the elements of x.<br />min(x)returns the smallest element of x.<br />[y, k] = min(x) (y is the smallest element of x and k is the index of y).<br />>> x = [0.9501 0.2311 0.6068 0.4860 0.8913];<br />length(x)<br />ans = 5<br />>> size(x)<br />ans = 1 5<br />>> sum(x)<br />ans = 3.1653<br />>> sort (x) <br />ans = 0.2311 0.4860 0.6068 0.8913 0.9501<br />>> [v, k] = min(x)<br />v = 0.2311<br />k = 1<br />Apply these same functions to arrays: <br />Essential property of such functions, applied now to matrices, is that thet they treat each column of a matrix as a distinct vector.<br />sort(A)sorts each column of A in ascending order.<br />sum(A)is a row vector whose elements are sums of columns of A.<br />size(A) returns a vector containing the number of rows & columns of A. <br />min(A) row vector containing the minimum of each column of A. <br />sum(A, 1) returns a vector whose elements are the sum of the columns of A.<br />sum(A, 2) returns a vector whose elements are the sums of the rows of A. <br />>> A = [9 897 44; 31 20 50; -75 -62 -98]<br />A =<br /> 9 897 44<br /> 31 20 50<br /> -75 -62 -98<br />>> sort (A)<br />ans =<br /> -75 -62 -98<br /> 9 20 44<br /> 31 897 50 <br /> <br />>> sum(A)<br /> ans = -35 855 -4<br /> <br />>> min (A)<br /> ans = -75 -62 -98<br /> <br /> >> size(A)<br /> ans = 3 3 <br /> <br />Additional Matrix Manipulation Functions:<br />reshape(A,m,n) change size. Reshape returns the m-by-n matrix whose elements are tak<br />en columnwise from X. <br />diag<br />tril<br />fliplr <br />rot90 <br />1.2.3 Extracting Elements via Subscripts and Colon Operators <br />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. <br />NOTE that the element index starts at 1 and zero or negative indices are NOT supported!<br />>> y(2) % NOTE: y defined previously <br />ans = .25000<br />>> A = [2 3 4; 5 6 7; 8 9 10]<br />A = 2 3 4<br /> 5 6 7<br /> 8 9 10<br />>> A(2, 1) %Identifies the individual element -- 2nd row, 1st column <br />ans = 5<br />>> A(3, 3) % Identifies the individual elements -- 3rd row 3rd column<br />ans = 10<br />More sophisticated identifications can be performed: <br />>> y(1:2:end) % elements from 1 to the end in steps of 2 <br />ans = 0 0.5000 1.0000<br />>> y([5 4 2 3]) % vector subscript<br />ans = 1.0000 0.7500 0.2500 0.5000<br /> >> A(1, :) % Identify first row<br /> ans =2 3 4<br />>> A(:, 1) % Identify first column <br /> ans = 2<br /> 5<br /> 8<br />>> A(2:3, 2:3)<br /> ans = 6 7<br /> 6 10<br />>> A(2:end, 2:end) % NOTE: the use of the end format<br /> ans = 6 7<br /> 9 10<br /> <br /> >> A(:, 3) % Identify the 3rd column <br /> ans =4<br /> 7 <br />10<br /> >> A(:, 3) = [-1; -2; -3] % Modify 3rd column <br /> A =2 3 -1<br /> 5 6 -2<br /> 8 9 -3<br />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: <br />>> A = [1 2 3; 4 5 6; 7 8 9]<br />A = 1 2 3<br /> 4 5 6<br /> 7 8 9<br />>> A(:) <br />1<br />4<br />7<br />2<br />5<br />8<br />3<br />6<br />9<br />1.2.4 Arithmetic Operations <br />Scalar operations: add (+), subtract(-), multiply (*), divide (/), & exponentiation (^). <br />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.<br />The precedence rules are ordered from the highest (1) to lowest precedence level (4): <br />Parentheses ().<br />Exponentiation (^).<br />Multiplication (*) and division (/).<br />Addition (+) and subtraction (-). <br />Within each precedence level, operators with equal precedence, say a multiplication and a division, are evaluated in order from left to right. <br />>> 2^4/10<br />ans = 1.6000<br />>> 5 + 4*9<br />ans = 41<br />>> -9 -8*2^2<br />ans = -41<br />>> 6 + 6/2*3<br />ans = 15<br />>> 6 + 6/(2*3)<br />ans = 7<br />>> 2^2^2<br />>> [2^2^4 2^(2^4)]<br />ans = 256 65536<br />Vector operations: <br />Vector arithmetic operation function element by element . NOTE: presence of the periods! <br />x.*y = [x1*y1 + x2*y2 + …].<br />x./y = [x1/y1 + x2/y2 + …].<br />x.^2 = [x1^2 + x2^2 + …].<br />NOTE: without period these operations are very different!<br />>> x.*y<br />ans = 0 0.0578 0.3034 0.3645 0.8913<br />>> y./x<br />ans = 0 1.0818 0.8240 1.5432 1.1220<br />>> x.^2<br />ans = 0 0.0534 0.3682 0.2362 0.7944<br />>> x*yERROR(explain below)<br />??? Error using ==> *<br />Bulk of MATLAB's Intrinsic functions work with vector inputs –<br />>> exp(x)<br />ans = 2.5860 1.2600 1.8346 1.6258 2.4383<br />>> sin(x)<br />ans = 0.8135 0.2290 0.5702 0.4671 0.7779<br />>> exp(-x).*sin(x) <br />ans = 0.3146 0.1818 0.3108 0.2873 0.3190<br />Array/Matrix Operations:<br />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.<br />>> A = [1 2; 3 4]; B = 3*ones(2)<br />A =<br /> 1 2<br /> 3 4<br />B =<br /> 3 3<br /> 3 3<br />>> A + B<br />ans =<br /> 5<br />6 7<br />>> A - B<br />ans =<br />-2 -1<br /> 0 1 <br />Array multiplication: C(i, j) = A(i, j).* B(i, j) <br /> >> A.*B <br /> ans = 3 6<br /> 9 12<br />NOTE the presence of the period before the asterisk.<br />Array division:C(i, j) = A(i, j)./ B(i, j)<br />>> A./B <br />ans = 3.3333 0.66667<br /> 1.0000 1.3333<br />NOTE the presence of the period before the slash.<br />Matrix Operations: <br />A ± B produce the same result as array additions/subtractions, and are valid only if A & B are the same size.<br />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 element–by-element array multiplication. Observe that <br /> <br />>> E = [1 2 3; 5 7 9]<br /> E = 1 2 3<br /> 5 7 9<br /> <br />>> G = [6 11; 21 -1; 19 77]<br />G = 6 11<br /> 21 -1<br /> 19 77<br /> <br />>> H = E*G<br />H = 105 240<br /> 348 741<br /> <br /> Matrix multiplication spelled out<br /> H = E * G <br /> H(i, j) = sum(E(i, :)*G(:, j)) <br />H(1, 1) = E(1, :) * G(:, 1) = [1 2 3]*[6 21 19]’ = 105 <br />Matrix multiplication is not commutative <br />>> G*E % G*E ≠ E*G<br />ans =<br /> 61 89 117<br /> 16 35 54<br /> 404 577 750<br />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 - <br />A*x = b<br />x & b are column vectors x = A (left division)<br /> <br />>> A = [3 2 1; -1 3 2; 1 -1 -1]<br />A = 3 2 1<br /> -1 3 2<br /> 1 -1 -1<br />>> b = [10;5;-1]<br />b = 10<br /> 5<br /> -1<br />>> x = A<br />x = 2.0000<br /> 1.0000<br /> 2.0000<br />>> ck = A*x – b % Checks OK => differences ~ 102eps<br />ck = <br /> 1.0e-014 *<br /> 0<br /> -0.1776<br /> 0.0222<br /> <br />1.2.5 Relational Operators<br />==equal <br />~=not equal <br /><less than <br />> greater than <br /> <=less than or equal <br />>=greater than or equal <br />Remember that a single = denotes assignment! Don't test for equality, using X =Y, which sets X equals the value of Y.<br />Result of relational operation -- <br /> 1 if relation is TRUE <br /> 0 if relation is FALSE <br />Scalars: <br />>> 3 > 2<br />ans = 1<br />>> 2 > 3<br />ans = 0<br />>> -4 <= -3<br />ans = 1<br />>> 1 < 1<br />ans = 0<br />>> 1 <= 1<br />ans = 1<br />>> 2 ~= 2<br />ans = 0<br />>> 3 == 3<br />ans = 1<br />>> 0 < 0.5 < 1 <br />ans = 0<br />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.<br />Arrays/Matrices: <br />>> B = 2.0*ones(3); <br />>> A = [1 2 3; 4 5 6; 7 8 9] <br />A =1 2 3<br /> 4 5 6<br /> 7 8 9<br />>> A == B<br />ans =0 1 0<br />0 0 0<br />0 0 0<br />>> A > B <br />ans =0 0 1<br />1 1 1<br />1 1 1<br />A number of relational functions: isequal, isempty, isfinite, isnan, etc <br />>> isequal(A, B)<br />ans = 0<br />>> A = [1 2 3; 5 6 7]<br />>> A == 7<br />ans =0 0 0<br />0 0 1<br />>> isequal (A, 7)<br />ans = 0<br />1.2.6 Logical Operators <br />& logical and<br />| logical or <br />~ logical not <br />Logical functions: <br />allTRUE if all elements are nonzero (don’t have to be 1s).<br />any TRUE if any element are nonzero (don’t have to be 1s).<br />As with relational operators, logical operations produce matrices of 0s & 1s. <br />Vectors: <br />>> x = [-1 1 1]; y = [1 2 -3]; <br />>> x > 0 <br />ans = 0 1 1<br /> >> y > 0 <br />ans = 1 1 0<br />>> x >0 & y > 0 <br />ans = 0 1 0<br />>> x > 0 | y > 0 % OR<br />ans = 1 1 1<br />>> any(x)<br />ans = 1<br />>> all(y) <br />ans = 1<br />Matrices: <br />all(X)operates on the columns of X, returning a row vector of 1's and 0's. <br />Similarly, any(X) operates on the columns of X, returning a row vector of 1's and 0's. <br />>> B = [9 8 7; 6 5 0; 0 0 1]<br />B =<br />9 8 7<br />6 5 0<br />0 0 1<br />>> all(B)<br />ans = 0 0 0<br />>> any(B)<br />ans = 1 1 1<br />To test equality of matrices using all, use nested functions OR use isequal<br />>> C = [19 8 7; 6 5 0; -3 0 1]<br />C = 19 8 7<br /> 6 5 0<br /> -3 0 1<br />>> all( all( C == B) )<br />ans = 0<br />>> any( any( C == B) )<br />ans = 1<br />>> isequal(B, C)<br />ans = 0<br />Logical function find: <br />A useful function is find, which returns the indices of the nonzero elements of a matrix. <br />>> x = [-3 1 0 -inf 0] <br />>> find(x == -inf)<br />ans = 4<br />>> f = find(x) <br />f = 1 2 4 <br />>> x(f) <br />ans = -3 1 -Inf <br />>> x(find(x < 0))<br />ans = -3 -Inf<br />>> A = [4 2 16; 12 4 3]<br />A = 4 2 16<br /> 12 4 3<br />>> B = [12 3 1; 10 -1 7]<br />B =12 3 1<br /> 10 -1 7<br />>> A < B<br />ans = 1 1 0<br /> 0 0 1<br />Can use find with matrix indices: <br /> >> [r, c] = find(A < B);<br /> >> [r c] % row & column indices <br /> ans = 1 1 <br /> 1 2<br /> 2 3<br />Say you want to set these elements of A to –9 <br />>> A([r c]) = -9;<br />>> A<br />A = -9 -9 16<br /> -9 4 3<br />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(:)).<br />1.3 FUNCTIONS<br />1.3.1 M-Files <br />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. <br />Why use: <br /> It is easier to edit a file of commands rather than retyping a long list of commands. <br />Makes a permanent record of your commands.<br />Creates procedures that can be reused at a later date.<br />Scripts: <br />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.<br />% contents of rainfall.m <br />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];<br />rain_sort = sort(rain)<br />rain_mean = mean(rain)<br />rain_med = median(rain)<br />rain_std = std(rain)<br />>> rainfall<br />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<br />rain_mean= 2.5558<br />rain_med = 2.3300<br />rain_std = 1.3376<br />>> whos % After running rainfall.m in the Command Window <br /> Name Size Bytes Class <br /> ans 1x12 96 double <br /> rain 1x12 96 double <br /> rain_mean 1x1 8 double <br /> rain_med 1x1 8 double <br /> rain_sort 1x12 96 double <br /> rain_std 1x1 8 double<br />. <br />Functions: - preferred approach<br />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.<br />Function m-files must start with the key word function -- <br />function [out_arg1, out_arg2, …] = name_of_function(in_arg1,in_arg2,…)<br />1) The first line of a function must begins with the KEYWORD function -<br />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.<br />b) The square bracket is then followed by the assignment symbol, =.<br />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. <br />d) The function name is followed by a comma separated list of input argument[s] placed inside parentheses, (). <br />2) It is suggested that a comment section, listing input/output arguments and a short description of the function’s 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 function’s input/output arguments. <br />3) The core of the procedure follows the comment section.<br />4) The function terminates when the last line is executed OR when the return statement is encountered. <br />A simple example of a user-constructed function is the following - <br />function [mean, standard_dev] = stats(x) <br /> %function [mean, standard_dev] = stats(x) <br /> % INPUT: <br /> % x vector <br /> % OUTPUT:<br /> % mean scalar <br /> % standard_dev scalar <br /> n = length(x); <br /> xb = sum(x)/n; <br /> standard_dev = sqrt(sum((x - xb).^2)/(n - 1)); <br /> mean = xb; <br />%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%<br />Examples of calling sequences are the following: <br />>> [r, a, z] = motion(x, y, t); <br />>> [r, p, q] = motion(x, y, [0:1:100])<br />>> [a, b, c] = motion(0.5, 12.0, 66.0); <br />1.3.2 Anonymous Functions<br />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 - <br />f1 = @(argument_list) expression<br />From the left:<br />f1 name or handle of the function,<br />= assignment operator,<br />@ function handle symbol,<br />(x,y, … ) a comma separated list of input arguments,<br />expression a single MATLAB expression, or command. <br />>> f1 = @(x) x^2 – 1; <br />>> f1(5)<br />ans = 24<br /> <br />If you want to input vectors, more care is needed in formulation! <br />>> f1( [4 5 6])<br />??? Error using ==> mpower <br />Matrix must be square. % Another unclear error message!<br />Here the function must be created in vector format, employing the period notation, <br />>> f1 = @(x) (x.^2 – 1); <br />>> f1( [ 4 5 6])<br />ans = 15 24 35<br />Anonymous functions can depend on multiple input variables:<br />>> g = @(u, v) u.^2 + v.^2;<br />1.3.3 Passing Functions as Arguments to other Functions<br />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. <br />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. <br /> <br />Calling Intrinsic MATLAB Functions <br />>> ezplot(sin) <br />??? Error using ==> sin<br />Not enough input arguments. <= opaque error message!<br />What happened here was that the input function was improperly called, but if one employs the symbol @ -- <br />>> ezplot(@sin) % it works <br />The preferred way to properly call a built-in function is to use a function handle.<br />Calling User-Created m-file Functions <br />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 <br />>> ezplot(f2)<br />??? Input argument "
x"
is undefined. <br />However, we can successfully plot the user created m-file function with a function handle - <br />>> ezplot(@f2) % works <br />Anonymous Functions <br />How does one pass an anonymous function to ezplot? Prior to our call to ezplot, we create an anonymous function, g, say the following - <br />>> g = @(x) cos(x.^2)<br />g = @(x)cos(x.^2)<br />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 -<br />>> ezplot(g) % works <br />1.4 FLOW CONTROL <br />1.4.1 if-end Expressions <br /> <br />Works best with scalars or arrays/matrices with certain logical functions (all, any)<br />if logical_condition_test_1 % Simplest form <br /> statements_1 <br />end <br />If logical_condition_test_1 is nonzero above, statements_1 are performed<br /> if logical_condition_test_2 <br /> statements_2 <br />else<br /> statements_3 <br />end <br />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. <br />if logical_condition_test_4 <br /> statements_4 <br />elseif logical_condition_test_5 <br /> statements_5<br /> else <br /> statements_6 <br />end <br />Logical condition tests usually are variables coupled by relational operators (x < 2.0) or logical functions, all(x < 0). <br />Simple if constructs can be written on a single line – <br />if x >= 0.0, y = sqrt(x), end <br />% Function example:<br />function [mean, standard_dev] = stats(x) <br /> [r, c] = size(x); <br /> % An error occurs if x is an array <br /> % Input of either a row or column vector is acceptable <br /> if r == 1 | c == 1; <br /> % c == 1 x => column vector <br /> % r == 1 x => row vector <br /> n = length(x); <br /> xb = sum(x)/n; <br /> standard_dev = sqrt(sum((x - xb).^2)/(n - 1)); <br /> mean = xb; <br /> else <br /> disp('You input an array & not a vector');<br /> end <br />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)! <br />1.4.2 For Loops<br />Used when you know ahead of time the number of iterations needed.<br /> for variable = expression <br /> statements <br /> end <br />expression of the form => lower:step:upper <br />NOTE: step can be a negative <br />NOTE: if step is omitted, it is assumed to be 1. <br />% Sum of first 25 terms of series 1/k<br />>> s = 0.0; % NOTE: must initialize s to 0.0 <br />>> for k = 1:25; s = s + 1.0/k; end <br />>> s<br />s = 3.8160<br />NOTE: loop expression can be defined in square bracket notation <br />>> for x = [pi/6. pi/4, pi/3], disp([x, sin(x)] ), end<br /> 0.5236 0.5000<br /> 0.7854 0.7071<br /> 1.0472 0.8660<br />1.4.3 While Loops<br />Used when know the number of iterations is not known prior to execution. <br />while logical_expression <br /> statements <br />end <br />NOTE: statements executed as long as logical_expression is true<br />function result = newton_sq_root(a) <br />% function result = newton_sq_root(a)<br />% Calculates a square of a number via Newton's method <br />% INPUT: a<br />% OUTPUT: result <br />old = realmax; % dummy start value <br />new = a/2; % Choice arbitrary <br /> while (abs((new - old)/new) > eps | abs(new – old) > eps)<br /> old = new;<br /> new = (old + a/old)/2;<br /> end <br />result = new;<br /> <br />>>newton_sq_root(10000.0)<br /> ans = 100 <br />You can employ while loops with the logical expression always set to true (1) but exit the loop with a break statement. <br />function result = newton_sq_rootB(a) <br />% function resultB = newton_sq_rootB(a)<br />% Calculates a square of a number via Newton's method <br />% INPUT: a<br />% OUTPUT: result <br /> <br /> old = realmax; % dummy start value <br /> new = a/2;<br /> while 1 % infinite loop <br /> old = new;<br /> new = (old + a/old)/2; <br /> % NOTE: reversed the criterion from above <br /> if abs((new - old)/new) <= eps; break; end <br /> end<br /> result = new;<br />>> newton_sq_rootB(10000.0)<br />ans = 100 <br />1.5 PLOTS<br />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 - <br />>> x = 0.0:1.0e-02:2*pi; y = sin(x).*exp(-x); <br />>> plot(x, y, ‘ro’);<br />1.5.1 Structure of a MATLAB Plot<br />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). <br />1.5.2 Interactive Plotting<br />This is the preferred approach in creating a plot; it minimizes the number functions you must remember!<br />Create some vectors in the command window:<br />>> x= 0:0.05:2*pi;<br />>> y = sin(x).*exp(-x);<br />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.<br />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 -- <br />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 -- <br />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! <br />Now plot a curve in three dimensions.<br />>> t = 0:0.05:10*pi;<br />>> y = sin(t).*exp(-t/10);<br />>> x = cos(t).*exp(-t/10);<br />>> z = t/10;<br />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.<br />In the Plotted Variables tab, type x, y, z. Then double click on plot3 panel icon. The Figure below results. <br />MATLAB graphics highly customizable!<br />I modified the above plot:<br />Thickened the line.<br />Colored the curve blue. <br />Increased the font size.<br />Labeled the axes.<br />Created a title and colored red.<br />1.5.3 Creation of Simple Plots via Command Line<br />MATLAB possesses powerful graphics capabilities. Start searching documentation with:<br />Help tab => Product Help => User Guides => Graphics => <br /> OR<br />fx => MATLAB => Graphics => Basic Plots and Graphs <br />Basic Plotting Commands<br />=> plot, plot3, loglog, semiplogx, semilogy, plotyy<br />>> x = [1.5 2.2 3.1 4.6 5.7 6.3 9.4]; <br />>> y = [2.3 3.9 4.3 7.2 4.5 3.8 1.1];<br />>> plot(x, y); % data points joined in sequence (See below)<br />>> plot(y); % y values plotted against their indices<br />Other 2D plots of interest:<br />logloglog-scaled axes<br />semilogxlog-scaled x axis<br />semilogy log-scaled y axis<br />barbar graph<br />histhistogram <br />Two useful graphics commands<br />gridadd major lines to current axes <br />zoom zoom in & out on 2D plots<br />1.5.4 Creating Multiple Curves in a Single Plot Frame<br />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 <br />Figure Palette 2D Axes Click on square made of 4 smaller squares Add Data tab –<br />OR use command-line subplot!<br />1.5.5 Plots of Functions <br />One can employ ezplot to create plots of functions:<br /> => ezplot(@f) plots the expression f = f(x) over the default domain: -2 < x < 2. <br />=> ezplot(@f,[min,max]) plots f = f(x) over the domain: min < x < max.<br />>> ezplot(@sin); <br />>> f = inline('cos(x).*exp(-x)');<br />>> ezplot(f)<br />1.5.6 How to Save a Figure <br /> File Generate m-file<br />Automatically create an m-file to reproduce figure!<br />NOTE: this function still requires input vectors! <br />File tab Save As a file <br />name_of_figure..fig MATLAB format ( you can load this figure via <br />Workspace icon)<br />name_of_figure2.emf for insert into Word <br />name_of_figure3.jpg for insert into Word <br />To insert the figure in a Word document:<br />[Figure 1] File Save Save as plot3.jpg [Saved in jpg format.]<br />[Word] Insert Picture From File … {plot3d.jpg}<br />Tried other file formats: emf, eps, pdf, & tif <br />Storage varies from plot.eps (5.3 M) to plot.pdf (13 KB).<br />
Tips For Beginners (Dorfman 2007; Driscoll 2009)
2.
Employ the up-arrow key to access previous commands. Type specific characters first and only matching commands are displayed.
3.
To interrupt a computation, type Ctrl-C in the command window.
4.
MATLAB possesses excellent debugging. Employ them, running your code step-by-step to identify errors.
5.
Modularize code into functional components, especially input, output, and core algorithm.
1.7 References<br />Burden, R. L., and Faires, J. D. Numerical Analysis, 7th Ed., 2001, (Brooks/Cole, Pacific Grove CA).<br />Dorfman, J. H. Introduction to MATLAB Programming, 2007 (Decagon: Berkeley, CA).<br />Driscoll, T. A. Learning MATLAB, 2009 (SIAM: Philadelphia, PA).<br />Hahn, B. D. Essential MATLAB for Scientists and Engineers, 2nd Ed, 2002 (Butterworth-Heinmann, Oxford, UK)<br />Hanselman D., and Littlefield, B. Mastering MATLAB 6, 2001 (Prentice Hall: Upper Saddle River, NJ). <br />Higham, D. J., and Higham, N. J., MATLAB Guide, 2nd Ed.,2005 (SIAM: Philadelphia, PA). <br />Hunt, B. R. et al, A Guide to MATLAB for Beginners and Experienced Users, 2001 (Cambridge University Press: Cambridge, UK). <br />Kelley, C. T., Solving Nonlinear Equations with Newton's Method, 2003 (SIAM: Philadelphia). <br />Pratap, R., Getting Started with MATLAB, A Quick Introduction for Scientists and Engineers, 2002 (Oxford University: Oxford, UK).<br />
Be the first to comment