University of Florida/Eml4500/f08.qwiki.bishop/MATLAB

Link to MATLAB Primer: http://apollo.mae.ufl.edu/~vql/courses/feem/matlab_primer_3rd.pdf

Accessing MATLAB
Almost all versions of MATLAB include an icon on the desktop in which you can open MATLAB. Also there is the option of going through the start menu. While in MATLAB, to exit the command is quit or exit.

Entering Matrices
In MATLAB, all entries are treated as a matrix. They can be only a 1x1 matrix, up to nxn matrices, where n is an integer. Scalars are considered 1x1 matrices and vectors are either 1 row or 1 column matrices.

There are multiple ways to write matrices in MATLAB. The following are two different codes for producing matrix A.

Input: A = [1 2 3; 4 5 6; 7 8 9] Output: A = 1    2     3       4     5     6       7     8     9

Input: A = [ 1 2 3   4 5 6    7 8 9] Output: A = 1    2     3    4     5     6    7     8     9 Complex numbers also have multiple ways of entering them into MATLAB. The following code demonstrates two approaches.

Input: A = [1 2; 3 4] + i*[5 6; 7 8] Output: A = 1.0000 + 5.0000i  2.0000 + 6.0000i 3.0000 + 7.0000i  4.0000 + 8.0000i

Input: A = [1+5i 2+6i; 3+7i 4+8i] Output: A = 1.0000 + 5.0000i  2.0000 + 6.0000i 3.0000 + 7.0000i  4.0000 + 8.0000i

The variables i or j are considered imaginary numbers but can be overwritten as regular variables. If this does happen then one can create a new name for the imaginary number by defining it in code. (jj = sqrt(-1) ).

Rectangular arrays consisting of numbers can be viewed from a file using MATLAB’s code:

load filename.ext.

The matrix may then be called up on MATLAB using its filename.

A special rule to note when involving exponential form is to avoid spaces else they will be viewed as two different objects (1.23e-10).

There are several already programmed functions to create matrices. One of which is rand, which creates a randomly numbered matrix. The function rand(n) will create a square matrix of n2 entries. However, if a rectangular matrix is desired, rand(m,n) produces a matrix m x n.

Input: rand(3) Output: ans = 0.9501   0.4860    0.4565    0.2311    0.8913    0.0185    0.6068    0.7621    0.8214

Input: rand(3,2) Output: ans = 0.4447   0.9218    0.6154    0.7382    0.7919    0.1763

Another built-in function that MATLAB contains is the magic command. magic(n) yields a matrix where no matter the size of the square matrix, all rows, columns, and diagonals will have the same sum.

Input: magic(5) Output: ans = 17   24     1     8    15    23     5     7    14    16     4     6    13    20    22    10    12    19    21     3    11    18    25     2     9

The final example of programmed functions in MATLAB is the Hilbert matrix. Typing hilb will yield a matrix with each element following the equation:.

Input: hilb(3) Output: ans = 1.0000   0.5000    0.3333    0.5000    0.3333    0.2500    0.3333    0.2500    0.2000

To call up a single entry from a matrix, one must use the format matrixname(i,j). The following is an example of this using the last version of matrix A.

Input: A(2,2) Output: ans = 4.0000 + 8.0000i

Matrix operations, array operations.
There are several operations in MATLAB that can be performed on matrices and scalars, including addition, subtraction, multiplication, power, conjugate transpose, and left and right division. The left and right division for matrices is shown below. Two rules to follow are:

If x = A\b then A*x=b (Using Gaussian elimination if A is square, else                                                    Householder orthogonalization.)

If x = b/A then x*A=b (Defined by b/A=(A'\b')'.)

where A is an invertible square matrix and b is a compatible column.

Input: A Output: A = 0    0     8     8     0     4     0    16     0

Input: b= [ 2 3 7; 5 4 3; 5 9 0] Output: b = 2    3     7     5     4     3     5     9     0

Input: x=A\b Output: x = 0.5000   0.3125   -0.0625     0.3125    0.5625         0     0.2500    0.3750    0.8750

Input: A*x Output: ans = 2    3     7     5     4     3     5     9     0

Input: x=b/A Output: x = 0.7500   0.2500    0.1875    0.0625    0.6250    0.2500   -0.3125    0.6250    0.5625

Input: x*A Output: ans = 2    3     7     5     4     3     5     9     0

Input: (A'\b')' Output: ans = 0.7500   0.2500    0.1875     0.0625    0.6250    0.2500    -0.3125    0.6250    0.5625

Array operations.

While the matrix operations mentioned above operate matrix-wise, they can be also used to operate entry-wise. If a period is added before the operation, then MATLAB will recognize this command as an entry by entry operation. Examples are shown below.

Input: [1,2,3,4].*[1,2,3,4] Output: ans = 1    4     9    16

Input: [1,2,3,4].^2 Output: ans = 1    4     9    16

Statements, expression, and variables; saving a session
When typing in commands or variables, MATLAB is case sensitive. Therefore, if variable A is assigned to a matrix then calling up a in the future will not bring up matrix A.

When entering a statement into MATLAB, it is stored into the memory either to the variable name assigned by the user or to ans which can be called back for future use. Statements usually end with the enter key, however if there is a comma or semicolon more than one statements may be made in the same line. Additionally instead of terminating the statement at the end of a line, a semicolon will continue until ended with the enter key without one.

To list all variables in the workspace, the command who or whos can be used. The variables can be reassigned or can be cleared from the memory. The command clear variable is used to clear the variable. Below are examples of the commands who and clear. clear alone deletes all user assigned variables. After logging out of a MATLAB session, all variable assignments are lost.

Input: who Output: Your variables are: A   ans  b    p    x

clear ans

If an operation is runaway or seems to never stop computing, pressing CTRL-C will break the computation in MATLAB.

To save the workspace before exiting, the command save will write all variables to a diskfile. After restarting MATLAB, the last workspace saved can be called back to its previous state with the command load. Input: save Output: Saving to: matlab.mat

Matrix building functions
A few matrix building functions include
 * eye : identity matrix
 * zeros: matrix of zeros
 * ones : matrix of ones
 * diag : create or extract diagonals
 * triu : upper triangular part of a matrix
 * tril : lower triangular part of a matrix
 * rand : randomly generated matrix
 * hilb : Hilbert matrix
 * magic : magic square
 * toeplitz : see help
 * zeros(m,n) produces an m-by-n matrix of zeros and zeros(n) produces an n-by-n one

Examples:

zeros(3)

ans = 0    0     0    0     0     0    0     0     0

zeros(2,3)

ans = 0    0     0    0     0     0

A = ans; zeros(size(A))

ans = 0    0     0    0     0     0

Diag(x) produces a matrix with the vector x down the diagonal; If A is a square matrix, then diag(A) is a vector consisting of the diagonal of A

Examples:

x = [1 2 3 4]; diag(x)

ans = 1    0     0     0    0     2     0     0    0     0     3     0    0     0     0     4

A = [1 2; 3 4]

A = 1    2    3     4

diag(A) ans = 1   4

diag(diag(A)) ans = 1    0    0     4

Matrices can be built from blocks; if A is a 3-by-3 matrix, then

A = ones(3,3); B = [A, zeros(3,2); zeros(2,3), eye(2)]

B = 1    1     1     0     0    1     1     1     0     0    1     1     1     0     0    0     0     0     1     0    0     0     0     0     1

For Loop
A For loop executes a block of code a specified number of times;

n=4; x=[]; for i=1:n, x=[x,i^2],end

x = 1

x = 1    4

x = 1    4     9

x = 1    4     9    16

m=3; for i=1:m, for j=1:n, H(i,j)=1/(i+j-1); end, end, H

H = 1.0000   0.5000    0.3333    0.2500    0.5000    0.3333    0.2500    0.2000    0.3333    0.2500    0.2000    0.1667

The semicolon in the above code suppresses printing of H, while the last H displays the final result, a hilbert matrix

While Loops
While loops allow their statements to be repeatedly executed as long as the relation remains true

a=5; n=0; while 2^n < a, n=n+1; end, n

n = 3

If Statement
The "if" statement executes the procedures inside the loop as long as the relation is true.

if n<0, parity = 0; elseif rem(n,2) == 0, parity = 2; else, parity = 1; end

parity

parity = 1

Relations
Here are the relation operators in MATLAB:
 * < less than
 * > greater than
 * <= less than or equal
 * >= greater than or equal
 * == equal
 * ~= not equal
 * note: "=" is used for assignment while "==" is used for relation

Relations can be connected or quantified by logical operators:
 * "&" and
 * "|" or
 * "~" not

When applied to scalars, a relation is actually the scalar 1 for true or 0 for false.

3<5   ans =   1

3>5   ans =   0

3==5   ans =   0

3==3   ans =   1

a = rand(5) a = 0.9355   0.3529    0.1987    0.7468    0.8462   0.9169    0.8132    0.6038    0.4451    0.5252   0.4103    0.0099    0.2722    0.9318    0.2026   0.8936    0.1389    0.1988    0.4660    0.6721   0.0579    0.2028    0.0153    0.4186    0.8381

b = triu(a)

b = 0.9355   0.3529    0.1987    0.7468    0.8462        0    0.8132    0.6038    0.4451    0.5252        0         0    0.2722    0.9318    0.2026        0         0         0    0.4660    0.6721        0         0         0         0    0.8381

a==b

ans = 1    1     1     1     1    0     1     1     1     1    0     0     1     1     1    0     0     0     1     1    0     0     0     0     1

A relation between matrices is interpreted by "while" and "if" to be true if each entry of the relation matrix is nonzero. For example if A and B are equal matrices, then if A==B, "statement"; end.

Scalar Functions
Certain functions operate on scalars, but operate element-wise when applied to a matrix. These functions are shown in the table below:


 * see help files for examples of these

Vector Functions
Some MATLAB functions operate on vectors, and for an m-by-n, where m is greater than or equal to 2, these functions operate on a column basis. Row-by-row fashion can be obtained by using the transpose of the function, hence mean(A')'. Here are a few of the vector functions available:

Example:

A = [1,2;3,4]

A = 1    2       3     4

max(max(A))

ans = 4

max(A)

ans = 3    4

Matrix Functions
MATLAB's real computing power comes from its matrix functions. Here are a few:
 * eig : eigenvalues and eigenvectors
 * chol : cholesky factorization
 * svd : singular value decomposition
 * inv : inverse
 * lu : LU factorization
 * qr : QR factorization
 * hess : hessenberg form
 * schur : schur decomposition
 * rref : reduced row echelon form
 * expm : matrix exponential
 * sqrtm : matrix square root
 * poly : characteristic polynomial
 * det : determinant
 * size : size
 * norm : 1-norm, 2-norm, F-norm, infinite-norm
 * cond : condition number in the 2-norm
 * rank : rank

Example:

A = rand(3,3)

A = 0.9649   0.9572    0.1419    0.1576    0.4854    0.4218    0.9706    0.8003    0.9157

eig(A)

ans = 1.8146             0.2757 + 0.3061i 0.2757 - 0.3061i

[U,D] = eig(A)

U = 0.4913            0.6696             0.6696              0.3158            -0.4476 + 0.2831i  -0.4476 - 0.2831i 0.8117           -0.2332 - 0.4655i  -0.2332 + 0.4655i

D = 1.8146                 0                  0                   0             0.2757 + 0.3061i        0 0                 0             0.2757 - 0.3061i

Command Line Editing and Recall
Editing the command line can be done using the left/right arrows, as well as the backspace button for deletion. To scroll through previously entered commands using the up/down arrows. This is much more efficient for small routines as switching between M-file and command window can be tedious.

Example:

a = rand(8)

a = Columns 1 through 6 0.5853   0.0759    0.0119    0.2630    0.1524    0.0046      0.5497    0.0540    0.3371    0.6541    0.8258    0.7749      0.9172    0.5308    0.1622    0.6892    0.5383    0.8173      0.2858    0.7792    0.7943    0.7482    0.9961    0.8687      0.7572    0.9340    0.3112    0.4505    0.0782    0.0844      0.7537    0.1299    0.5285    0.0838    0.4427    0.3998      0.3804    0.5688    0.1656    0.2290    0.1067    0.2599      0.5678    0.4694    0.6020    0.9133    0.9619    0.8001    Columns 7 through 8 0.4314   0.5499      0.9106    0.1450      0.1818    0.8530      0.2638    0.6221      0.1455    0.3510      0.1361    0.5132      0.8693    0.4018      0.5797    0.0760

a = inv(a)

a = Columns 1 through 5 -0.7806   4.7641   -0.5126    0.4986    3.2273   -2.5268   13.4861   -2.1132    4.5763    8.5986    2.8760  -22.3594    2.5534   -6.6821  -12.7484    3.8710  -20.5717    3.3312   -6.3999  -11.6863   -3.2488   31.3116   -5.4853   10.5614   18.0258   -1.0536   -7.8019    2.5877   -3.0862   -5.2544    0.3442   -0.5124   -0.2746   -0.3617   -0.7195    1.7237   -4.8181    0.9024   -0.5737   -3.1429  Columns 6 through 8 0.0232  -2.3877   -4.2041   -2.4798   -5.7673  -13.6525    4.5481   10.2127   22.0422    2.0557    8.5971   20.8620   -5.0720  -15.0243  -30.6600    1.6697    4.5284    7.7693    0.0589    1.2575    0.8056    0.5811    2.1432    3.7028

Submatrices and Colon Notation
Colon notation is used to generate vectors and reference submatrices. It accomplishes similar functions to the for statement. For an example in generating vectors the input

0:0.2:1

creates the output line vector

[0, 0.2, 0.4, 0.6, 0.8, 1].

With colon notation the beginning value, increment, and ending value can all be specified. This notation is handy when graphing functions and needing specific increments on the x-axis.

For an example in referencing submatrices:

A(1:3,4)

is the column vector of the first three entries of the fourth column.

A(:,4)

is the entire fourth column.

A(:,[1 3]

is columns 2 and 4 of A.

A(:,[2 4 5] ) = B(:,1:3)

replaces columns 2, 4, and 5 of A with the first three columns of B.

M-files
M-files are files stored as either “script files” or “function files” with file type of “.m”. A script file consists of normal MATLAB statements. For example if there is a file file.m then the command file would input all the statements in the m-file. However, be careful because calling the m-file will overwrite any information that conflicts.

Function files take input from MATLAB perform an operation and then provide an output back to MATLAB. For example the function randint.m,

Function a = randint(m,n) %RANDINT Randomly generates intergral matrix. %randint(m,n) returns an m-by-n matrix with entries %between 0 and 9. %Rnad(m,n,a,b) return entries between integers a and b.  If nargin < 3, a=0; b = 9; end a = floor((b-a+1)*rand(m,n) +a;

If this function is called by z = randint(4,5), then 4 and 5 are passed to the variable m and n and the out of the m-file is assigned to the variable z. Some MATLAB functions are built in to the program but you can create your own as well.

Text Strings, Error Messages, Input
Text strings are entered into MATLAB by single quotes, for example ‘MATLAB’. The display command,

disp(‘MATLAB’)

displays the text inside the parentheses. There is also an error function available for notifying a user that their input into a m-file causes an error,

error(‘Sorry, error’)

and when placed in an m-file the error command aborts the m-file. Also, a user can be prompted to input data into an m-file with the command,

input(‘Enter a value: ’).

Managing M-Files
When using Matlab, it is sometimes necessary to move to another workspace (text editor, graphic viewer, etc.) while MATLAB is still active. The !- feature can be used to prevent exiting MATLAB while performing operations in a separate program. For instance, one can edit the file EML4500.m in a local text editor by typing

When the user is finished editing the file, they will be returned to an active MATLAB window.

M-files should be stored in a dedicated directory so that they can be easily accessed by MATLAB. The default active directory of MATLAB is C:\Program Files\MATLAB\R2006\work, but the user may choose to create another active work directory. To change the active directory or to create an additional MATLAB search path, navigate to File -> set Path... and perform any necessary changes. Note that MATLAB does include subdirectories in its search path, which allows the user to save M-files in subfolders and still be able to execute them in a MATLAB session.

The table below lists commands that will be useful when working with M-files:

Comparing efficiency of algorithms: Flops, tic and toc
When creating computer-intensive MATLAB code, it is often wise to create an algorithm that is efficient as possible. Two way to asses the efficiency of an algorithm are the amount of floating point operations (flops) performed and the elapsed time.

The MATLAB function records the total number of flops performed. The command  resets the flops to zero and is normally entered prior to running a an algorithm. Entering the  command after executing the algorithm gives the flops count for the algorithm. For example, the number of flops required to solve the equation c = a + b can be obtained with:

NOTE: With MATLAB ver. 7 and newer, the  command can no longer be used. MATLAB will display the following error:

function f = flops(x) %FLOPS Obsolete floating point operation count. %  Earlier versions of MATLAB counted the number of floating point %  operations. With the incorporation of LAPACK in MATLAB 6, this %  is no longer practical. %  Copyright 1984-2004 The MathWorks, Inc.     %   $Revision: 5.12.4.1 $  $Date: 2004/01/24 09:21:21 if (nargin < 1) || (x ~= 0) warning('MATLAB:flops:UnavailableFunction', ...       'Flop counts are no longer available.') end if nargout > 0 f = 0; end

While the flops command may not work for all users, the elapsed time can still be obtained. The time required to solve an algorithm can be found by using the stopwatch timers  and. For example, to find the total time needed to solve the equation, use the following command;

It should be noted, however, that the elapsed time may not be the best measure of algorithm efficiency because the rate of execution depends on how busy the processor is.

Output format
Even though all computations in MATLAB are performed in double precision, the format of the output display can be altered by the following commands:

Once introduced, the chosen format will remain in effect until changed.

The command  will suppress blank line allowing more information to be seen on the screen.

The command  returns MATLAB to the non-compact format.

Hardcopy
The Hardcopy function is used to save your work to a file on your computer. To use this feature, the user enters in “diary filename” where filename is the desired name of the file. If no name is given, the file will automatically be called diary. The file can be edited as desired and printed using the !-feature.

Graphics
To graph a planar plot in MATLAB, one can use the plot function. Once the x and y vectors and defined by the user, a graphic plot can be obtained by entering “plot(x,y).” Sample code is provided as an example.

x=-4:.01:4 y=sin(x) plot(x,y)

This will open up a window with the graph, called figure 1. To open a new blank figure without editing the old one, the user can type in “figure(2).” This new figure is now the active graph, and any code entered will only effect this window. The user can enter in “figure(1)” to make the old figure active when so desired.

Graphing over an interval of numbers can be done by placing a colon on either side of the values of x. For example,

x=-1.5:.01:1.5

will set x to the value of .01 only over the interval from -1.5 to 1.5.

Graphs can also be produced by using the fplot command. Typing in “fplot(‘functionname’)” will graph a function that has been previously saved as an M-file.

To make a parametric plot, simply enter in the values for x,y, and t. Sample code is provided.

t=0:.001:2*pi x=cos(3*t) y=sin(2*t) plot(x,y)

Once a plot is made, the axis and title can be edited using the “title”, “xlabel”, and “ylabel” commands. “gtext” Will place a text box at a point specified by the user with the mouse. “text” will place a text box at the given coordinates. A samlple title code is given below.

title(‘Best Least Squares Fit’)

The axis can also be edited by using the “axis([xmin,xmax,ymin,ymax])”, “axis(axis)”, “axis auto”, “v=axis”, “axis square”, “axis equal”, “axis off”, and “axis on” commands.

To plot multiple y functions on a single graph, one can designate multiple y values. Sample code is provided.

x=0:.01:2*pi y1=sin(x) y2=sin(2*x) y3=sin(4*x) plot(x,y1,x,y2,x,y3)

This same feature can be done by creating a Y matrix and then plotting that matrix with respect to x.

x=0:.01:2*pi Y=[sin(x)',sin(2*x)',sin(4*x)'] plot(x,Y)

Multiple plots on the same graph can also be achieved with the hold command. Entering “hold” will cause MATLAB to plot all subsequent graphs on the current active window.

It is also possible to change the color and type of the data line as well as the color and type of the data points. Sample code is provided.

x=0:.01:2*pi y1=sin(x) y2=sin(2*x) y3=sin(4*x) plot(x,y1,'--',x,y2,':',x,y3,'+') plot(x,y,'r--')

That code will cause y1 to be plotted with a dashed line, y2 to be plotted with a dotted line, and y3 to have a plus sign an each data point. The r before the “—“ in the last line of code will cause the dashed line to be red.

The command subplot will place several smaller plots on the same figure.

To print a hardcopy of a graphic, one can use the print command. If the command is followed by the filename, MATLAB will save the graphic file to the computer. The graphic can be appended if edited by entering “print –append filename”.

MATLAB is also capable of producing 3-D plots. Sample code for producing a parametric 3-D plot is given below.

t-.01:.01:20*pi x=cos(t) y=sin(t) z=t z=t.^3 plot3(x,y,z)

The title, data points, and axis can be label and edited just as a 2-D plot could be.

MATLAB can also render various graphical effects, such as a mesh grid or surf plot. The “mesh” command will produce a mesh over the surface of the graph, while surf will produce a shaded surface over the graph. Sample code to produce a mesh graph is shown below.

xx=-2:.2:2 yy=xx [x,y]=mesh grid(xx,yy) z=exp(-x.^2 - y.^2) mesh(z)

Entering in “surf(z)” would turn this graph into a surf plot.

The shading schemes of the surface can be edit using the “faceted”, “interpolated”, and “flat” commands. The color schemes available in MATLAB are “hsv”, “hot”, “cool”, “jet”, “pink”, “copper”, “flag”, “gray”, and “bone”.

Parametric surface plots can be made using the sphere and cylinder commands. The following sample code is an example of how to graph a torus.

function [x,y,z] = torus(r,n,a) if nargin < 3, a=1; end if nargin < 3, a=1 if nargin < 2, n = 30 if nargin < 1, r = 0.5 theta = pi*(0:2:2*n)/n phi = 2*pi*(0:2:n)'/n xx = (a + r*cos(phi))*cos(theta) yy = (a + r*cos(phi))*sin(theta) zz = r*sin(phi)*ones(size(theta)) if nargout == 0 surf(xx,yy,zz) ar = (a+r)/sqrt(2) axis([-ar,ar,-ar,ar,-ar,ar]) else x=xx y=yy z=zz end

Sparse Matrix Computations
MATLAB can reduce a matrix to a “sparse” matrix by only saving the elements in the matrix that are non-zero. Therefore, it can perform calculations faster by storing a matrix as a sparse matrix rather than a full “dense” matrix. The commands “full” and “sparse” are used to change a matrix to either type. The following code will create a sparse matrix.

F=floor(10*rand(6)) F=triu(tril(F,1),-1) S=sparse(F)

To return this matrix to full, enter the command “F=full(S)”. It is also possible to see if a matrix is full or sparse using the “issparse(F)” command.

To create a sparse banded matrix using the spdiags command, use the following code.

m=6 n=6 e=ones(n,1) d=-2*e T=spdiags([e,d,e],[-1,0,1],m,n)

Another way to enter in a sparse matrix is to only enter in the non-zero elements. Example code for this is shown below.

i=[1 2 3 4 4 4] j = [1 2 3 1 2 3] s = [5 6 7 8 9 10] S=sparse(i,j,s,4,3), full(S)

Operations can by applied to any matrix regardless if it is sparse or full.