matlab basics

48
1 MATLAB ESSENTIALS PHYS100 1.1 BASICS 1.1.1 Start and Termination of a MATLAB Session 2 1.1.2 Desktop Environment 2 1.1.3 Saving Variables and Command Window Session & Variables 8 1.1.4 Floating-Point (Real) Numbers 9 1.1.5 Additional MATLAB Data Classes 10 1.2 MATRICES AND VECTORS 1.2.1 Creation of Vectors 12 1.2.2 Functions to Manipulate Vectors, Matrices, and Arrays 15 1.2.3 Extract Elements via Subscripts and Colon Operators 16 1.2.4 Arithmetic Operators 18 1.2.5 Relational Operators 21 1.2.6 Logical Operators 23 1.3 FUNCTIONS 1.3.1 M Files 25 1.3.2 Anonymous Functions 26 1.3.3 Passing Functions as Arguments to other Functions 27 1.4 FLOW CONTROL 1.4.1 if-end Expressions 28 1.4.2 for Loops 29 1

Upload: butest

Post on 17-May-2015

3.514 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: MATLAB BASICS

1 MATLAB ESSENTIALS PHYS100 1.1 BASICS

1.1.1 Start and Termination of a MATLAB Session21.1.2 Desktop Environment 21.1.3 Saving Variables and Command Window Session & Variables81.1.4 Floating-Point (Real) Numbers 91.1.5 Additional MATLAB Data Classes 10

1.2 MATRICES AND VECTORS 1.2.1 Creation of Vectors 121.2.2 Functions to Manipulate Vectors, Matrices, and Arrays151.2.3 Extract Elements via Subscripts and Colon Operators 161.2.4 Arithmetic Operators 181.2.5 Relational Operators 211.2.6 Logical Operators 23

1.3 FUNCTIONS 1.3.1 M Files 251.3.2 Anonymous Functions 261.3.3 Passing Functions as Arguments to other Functions 27

1.4 FLOW CONTROL 1.4.1 if-end Expressions 281.4.2 for Loops 291.4.3 while Loops 29

1.5 PLOTS1.5.1 Structure of a MATLAB Plot 311.5.2 Interactive Plotting 311.5.3 Creation of Simple Plots via Command Line 351.5.4 Generation of Multiple Curves in a Single Plot Frame 351.5.5 Plots of Functions 361.5.6 How to Save a Figure 36

1.6 TIPS FOR BEGINNERS 37

1.7 REFERENCES 37

1

Page 2: MATLAB BASICS

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 manipu-lation 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 per-forming numerical computations. It primary strengths are rapid code prototyping and data manipulation due to its strengths in matrix computations and graphics. It is excellent envi-ronment 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 win-dows 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 direc-tory 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

2

Page 3: MATLAB BASICS

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*7ans =

42Alternatively, to suppress such blank lines permanently change the Numeric display set-ting 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 = 1ans = 0.7071

Employ the = symbol to assign values to variables -

>> x = exp(2), y = cos(0.25*pi), z = x + yx = 7.3891y = 0.7071z = 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 3.14159265358979i, j (-1.0)0.5

Inf result of n/0, where n is any non-zero real numberNaN 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 casecatchclassdef continueelse

3

Page 4: MATLAB BASICS

elseif end

forfunctionglobalifotherwiseparfor persistentreturnspmdswitchtrywhile

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 con-tinuation of the expression on the next line in the Command Window environment.

4

Page 5: MATLAB BASICS

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 func-tion 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 MAT-LAB, 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 ar-rays. 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

5

Page 6: MATLAB BASICS

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 com-puter 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 Navi-gator, 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

6

Page 7: MATLAB BASICS

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/Debug-ger 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 sym-bol to the immediate left of the active command prompt, >> and a screen similar to that below appears –

7

Page 8: MATLAB BASICS

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 Re-sources => The MathWorks Web Site.

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

MATLAB@ 7 Getting Started Guide (getstart.pdf) (260 pg.)

MATLAB@ 7 Desktop Tools and Development Environment (matlab_env.pdf) (957 pg.)

MATLAB@ 7 Mathematics (math.pdf) (443 pg.)

MATLAB@ 7 Programming Fundamentals (matlab_prog.pdf) (837 pg.)

MATLAB@ 7 Programming Tips (programming_tips.pdf) (65 pg.)

MATLAB@ 7 Object-Oriented Programming (matlab_oop.pdf) (437 pg.)

MATLAB@ 7 Data Analysis (data_analysis.pdf) (216 pg.)

MATLAB@ 7 Graphics (graphg.pdf) (671 pg.)

MATLAB@ 7 3D Visualization (visualize.pdf) (212 pg.)

MATLAB@ 7 Function Reference: A-E (refbook.pdf) (1378 pg.)

8

Page 9: MATLAB BASICS

MATLAB@ 7 Function Reference: F-O (refbook2.pdf) (1732 pg.)

MATLAB@ 7 Function Reference: P-Z (refbook3.pdf) (1802 pg.)

An Additional MATLAB Resource:

Electronic Resources at http:/libraries.claremont.edu

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'). 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

>> 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 stor-age, 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 Com-mand 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

9

Page 10: MATLAB BASICS

>> 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 limita-tions 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 er-ror, at which calculations are performed –

>> epsans = 2.2204e-016

The fundamental parameter eps also represents between a number and the next great-est 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.0ans = Infans = -Inf

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,

>> realmax(‘double’)ans = 1.797693134862316e+308>> realmax (‘double’)+ 1.0e291ans = 1.797693134862316e+308>> realmax(‘double’) + 9.0e291ans = 1.797693134862316e+308>> realmax(‘double’) + 1.0e292ans = 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 accu-racy. Such numbers are termed normal double-precision variables. Note you create num-bers smaller than realmin, but at the cost of greatly reduced precision. However numbers less than eps*realmin are set to zero.

10

Page 11: MATLAB BASICS

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 intrin-sic 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.6551i

0.7547 - 0.1626i 0.2760 - 0.1190i 0.6797 - 0.4984i

>> class(z)ans = double

Note that complex numbers do NOT constitute a distinct data class. Such numbers by de-fault store their real and imaginary components in double precision.

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 pre-cision 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.

>> 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 ar-rays are also created by the relational operators (==,<,>,~, etc.) and functions like any, all, isnan, isinf, and isfinite.

11

Page 12: MATLAB BASICS

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 gen-erate 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 fol-lowing a scalar structure is created with three fields -

>> S.name = 'john smith';>> S.score= 89;>> S.grade= 'B+';>> class(S)ans = struct>> SS = name: 'john smith'score: 89grade: 'B+'

1.2 MATRICES, ARRAYS, AND VECTORS

1.2.1 Creation of Vectors, Matrices, and Arrays12

Page 13: MATLAB BASICS

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] % [1 by 3 row vector]a = 1 2 3

Column vector => separate elements by semicolons and enclose the vector with square brackets, [].

>> c = [4; 5; 6] % [3 by 1 column vector]c = 4

56

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

Arrays/matrices can be constructed explicitly using [] notation with the ends of rows speci-fied 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 2 3 4>> e = [d c]e = 1 2 5 3 4 6>> f = [[e e]; [a b a]]f = 1 2 5 1 2 5 3 4 6 3 4 6 1 2 3 4 1 2

The colon operator can be used to construct vectors:

13

Page 14: MATLAB BASICS

vector = lowest value : positive step : greatest value or vector = greatest value : nega-tive step: lowest value -

>> x = 0.3*(0.0:.05:.15)x = 0 0.0150 0.0300 0.0450

>> y = 10:-2:0 y = 10 8 6 4 2 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) => m-by-n matrix of 0s.ones(n) => n-by-n matrix of 1s.eye(n) => n-by-n identity matrix. rand(n) => n-by-n matrix of uniformly distributed random numbersrandm(n) => n-by-n matrix of normally distributed random numbersrandi(imax, [m,n]) => returns an m-by-n matrix of random integers uniformly between 1 and imax.repmat(A, m, n) => creates a large matrix B consisting of an m-by-n tiling of copies of A.

>> rs = rand % Calling rand without attributes generates scalar random numbersrs = 0.9853

>> r = rand(3,1)r =

0.8147 0.9058 0.1270

>> r = rand(1,5)r = 0.9134 0.6324 0.0975 0.2785 0.5469

>> eye(3)ans = 1 0 0 0 1 0 0 0 1

>> zeros(2) ans = 0 0 0 0

14

Page 15: MATLAB BASICS

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

>> rand(3) % for details ans = 0.4860 0.4565 0.4447 0.8913 0.0185 0.6154 0.7621 0.8214 0.7919

>> A = randi(100, [8,8])A = 65 6 98 97 22 58 10 6 21 61 100 73 84 46 4 37 38 6 79 42 63 5 62 64 79 42 44 75 14 3 61 72 69 31 50 27 21 32 2 70 47 88 22 44 61 2 2 9 57 2 65 94 63 39 20 46 80 77 33 69 38 69 59 45

>> A = [1 2; 3 4];>> B = repmat(A, [3,3])B = 1 2 1 2 1 2 3 4 3 4 3 4 1 2 1 2 1 2 3 4 3 4 3 4 1 2 1 2 1 2 3 4 3 4 3 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 trans-pose of row vector is a column vector. The transpose of column vector is a row vector.

>> y = 10:-2:0 y = 10 8 6 4 2 0

>> y’ ans =

10 8

15

Page 16: MATLAB BASICS

6420

>> 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 % some familiar vector functions w = 5 6 7 8 9 10>> dot(w,y)ans = 190

>> cross(w(1:3), y(1:3)) % some familiar vector functionsans = -20 40 -20

Some more functions which can be applied to vectors:

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

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

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) sorts each column of A in ascending order.sum(A) is a row vector whose elements are sums of columns of A.size(A) returns a vector containing the number of rows & columns of A.

16

Page 17: MATLAB BASICS

min(A) row vector containing the minimum of each column of A. sum(A, 1) returns a vector whose elements are the sum of the columns of A.sum(A, 2) returns a vector whose elements are the sums of the rows of A.

>> 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 855 -4

>> min (A) ans = -75 -62 -98

>> size(A) ans = 3 3

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 sub-script/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) % NOTE: y defined previously ans = .25000

>> A = [2 3 4; 5 6 7; 8 9 10]A = 2 3 4 5 6 7 8 9 10

>> A(2, 1) %Identifies the individual element -- 2nd row, 1st column ans = 5>> A(3, 3) % Identifies the individual elements -- 3rd row 3rd columnans = 10

17

Page 18: MATLAB BASICS

More sophisticated identifications can be performed:

>> y(1:2:end) % elements from 1 to the end in steps of 2 ans = 0 0.5000 1.0000

>> y([5 4 2 3]) % vector subscriptans = 1.0000 0.7500 0.2500 0.5000

>> A(1, :) % Identify first row ans = 2 3 4

>> A(:, 1) % Identify first column ans = 2 5 8

>> A(2:3, 2:3) ans = 6 7 6 10

>> A(2:end, 2:end) % NOTE: the use of the end format ans = 6 7

9 10

>> A(:, 3) % Identify the 3rd column ans = 4

7 10

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

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, con-structed 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(:) 147258369

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

18

Page 19: MATLAB BASICS

order is set by rules of precedence. Precedence levels determine the order in which MAT-LAB, 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) Parentheses ().2) Exponentiation (^).3) Multiplication (*) and division (/).4) 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.

>> 2^4/10ans = 1.6000>> 5 + 4*9ans = 41>> -9 -8*2^2ans = -41>> 6 + 6/2*3ans = 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 = [x1*y1 + x2*y2 + …].x./y = [x1/y1 + x2/y2 + …].x.^2 = [x1^2 + x2^2 + …].

NOTE: without period these operations are very different!

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

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

Bulk of MATLAB's Intrinsic functions work with vector inputs –

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

19

Page 20: MATLAB BASICS

Array/Matrix Operations:

Some (*, /, ^) arithmetic operations function differently for arrays and matrices. Matrix op-erations 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 ar-rays.

>> A = [1 2; 3 4]; B = 3*ones(2)A = 1 2 3 4B = 3 3 3 3

>> A + Bans =

4 56 7

>> A - Bans =

-2 -1 0 1

Array multiplication: C(i, j) = A(i, j).* B(i, j)

>> A.*B ans = 3 6 9 12

NOTE the presence of the period before the asterisk.

Array division: C(i, j) = A(i, j)./ B(i, j)

>> A./B ans = 3.3333 0.66667

1.0000 1.3333

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 element–by-element array multiplication. Observe that

20

Page 21: MATLAB BASICS

>> E = [1 2 3; 5 7 9]

E = 1 2 3 5 7 9

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

21 -1 19 77

>> H = E*G

H = 105 240 348 741

Matrix multiplication spelled out

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

Matrix multiplication is not commutative

>> G*E % G*E ≠ E*Gans =

61 89 117 16 35 54 404 577 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 compo-nents are known but x is nx1 vector whose elements are unknown -

A*x = b

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

21

Page 22: MATLAB BASICS

>> 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\bx = 2.0000

1.0000 2.0000

>> ck = A*x – b % Checks OK => differences ~ 102epsck =

1.0e-014 * 0 -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.

22

Page 23: MATLAB BASICS

Result of relational operation -- 1 if relation is TRUE 0 if relation is FALSE

Scalars:

>> 3 > 2ans = 1

>> 2 > 3ans = 0

>> -4 <= -3ans = 1>> 1 < 1ans = 0

>> 1 <= 1ans = 1

>> 2 ~= 2ans = 0

>> 3 == 3ans = 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] A = 1 2 3

4 5 6 7 8 9

>> A == Bans = 0 1 0

0 0 00 0 0

>> A > B ans = 0 0 1

1 1 11 1 1

A number of relational functions: isequal, isempty, isfinite, isnan, etc

>> isequal(A, B)ans = 0

>> A = [1 2 3; 5 6 7]

23

Page 24: MATLAB BASICS

>> A == 7ans = 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 TRUE if all elements are nonzero (don’t have to be 1s).any TRUE if any element are nonzero (don’t 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 1 1

>> y > 0 ans = 1 1 0

>> x >0 & y > 0 ans = 0 1 0

>> x > 0 | y > 0 % ORans = 1 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.

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 76 5 00 0 1

>> all(B)ans = 0 0 0

24

Page 25: MATLAB BASICS

>> any(B)ans = 1 1 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 4

>> x(f) ans = -3 1 -Inf

>> x(find(x < 0))ans = -3 -Inf

>> A = [4 2 16; 12 4 3]A = 4 2 16

12 4 3

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

>> A < Bans = 1 1 0

0 0 1

Can use find with matrix indices:

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

ans = 1 1 1 2 2 3

Say you want to set these elements of A to –9

25

Page 26: MATLAB BASICS

>> A([r c]) = -9;>> AA = -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 se-quence 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 re-main in the Workspace. Scripts overwrite preexisting variables in the Workspace. CAU-TION – when using scripts you can make unintended modifications of workspace vari-ables. 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)

>> rainfallrain_sort= 0.17 0.93 1.58 1.90 2.19 2.22 2.44 3.23 3.47 3.82 3.97 4.75rain_mean= 2.5558rain_med = 2.3300rain_std = 1.3376

>> whos % After running rainfall.m in the Command Window Name Size Bytes Class ans 1x12 96 double rain 1x12 96 double rain_mean 1x1 8 double rain_med 1x1 8 double rain_sort 1x12 96 double rain_std 1x1 8 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

26

Page 27: MATLAB BASICS

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 argu-ments (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 de-scription of the function’s purpose, be placed immediately following the function line. These comments, immediately following the 1st line, are displayed on the command win-dow, if one types >> help function_name. This is a useful way to inform the function user of function’s 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 en-countered.

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 = length(x); xb = sum(x)/n; standard_dev = sqrt(sum((x - xb).^2)/(n - 1)); mean = 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

27

Page 28: MATLAB BASICS

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 func-tions in the command window or in a parent m-file by simply typing the following -

f1 = @(argument_list) expression

From the left:f1 name or handle of the function,= assignment operator,@ function handle symbol,(x,y, … ) a comma separated list of input arguments,expression 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 va-riety of tasks - solve integrations and ordinary differential equations, etc. In other words, functions must be able to call other functions. Obviously MATLAB must discriminate some-how 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 ==> sinNot 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

28

Page 29: MATLAB BASICS

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

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 cre-ate 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, ex-ists 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 % Simplest form statements_1

end

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

29

Page 30: MATLAB BASICS

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).

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 >> ss = 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

30

Page 31: MATLAB BASICS

1.4.3 While Loops

Used when know the number of iterations is not known prior to execution.

while logical_expression statements

end

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 com-mand 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);

31

Page 32: MATLAB BASICS

>> plot(x, y, ‘ro’);

0 1 2 3 4 5 6 7-0.05

0

0.05

0.1

0.15

0.2

0.25

0.3

0.35

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

32

Page 33: MATLAB BASICS

This is the preferred approach in creating a plot; it minimizes the number functions you must remember!

Create some vectors in the command window:>> 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 rec-tangle with blue curve). On the right of this icon, activate the pull-down plot menu by click-ing & 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 --

33

Page 34: MATLAB BASICS

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 Fig-ure. If relevant item does not appear, then double click on the curve. Now you can label the appropriate axes!

34

Page 35: MATLAB BASICS

Now plot a curve in three dimensions.

>> t = 0:0.05:10*pi;>> y = sin(t).*exp(-t/10);>> x = cos(t).*exp(-t/10);>> z = 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!

35

Page 36: MATLAB BASICS

I modified the above plot: Thickened the line. Colored the curve blue. 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 3.1 4.6 5.7 6.3 9.4]; >> y = [2.3 3.9 4.3 7.2 4.5 3.8 1.1];>> plot(x, y); % data points joined in sequence (See below)>> plot(y); % y values plotted against their indices

Other 2D plots of interest:loglog log-scaled axessemilogx log-scaled x axissemilogy log-scaled y axisbar bar graphhist histogram

Two useful graphics commandsgrid 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 –

36

Page 37: MATLAB BASICS

OR use command-line subplot!

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);

-6 -4 -2 0 2 4 6

-1

-0.5

0

0.5

1

x

sin

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

37

Page 38: MATLAB BASICS

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

-40

-20

0

20

40

60

x

cos(x) exp(-x)

1.5.6 How to Save a Figure

File Generate m-fileAutomatically 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 al-gorithm.

Effectively use The Help and Debugging tools.

38

Page 39: MATLAB BASICS

Use the M-Lint code checker to identify problems in your code.

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-Hein-mann, 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 (Cam-bridge 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).

39