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

## Sections 1-4

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

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

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

A =

```    1     2     3
```
```    4     5     6
```
```    7     8     9
```

EDU>> A= [

1 2 3

4 5 6

7 8 9]

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.

EDU>> A = [1 2; 3 4] + i*[5 6; 7 8]

A =

```  1.0000 + 5.0000i   2.0000 + 6.0000i
```
```  3.0000 + 7.0000i   4.0000 + 8.0000i
```

EDU>> A = [1+5i 2+6i; 3+7i 4+8i]

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:

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.

EDU>> rand(3)

ans =

```   0.9501    0.4860    0.4565
```
```   0.2311    0.8913    0.0185
```
```   0.6068    0.7621    0.8214
```

EDU>> rand(3,2)

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.

EDU>> magic(5)

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

EDU>> hilb(3)

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.

EDU>> A(2,2)

ans =

```  4.0000 + 8.0000i
```

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

EDU>> A

A =

```    0     0     8
```
```    8     0     4
```
```    0    16     0
```

EDU>> b= [ 2 3 7; 5 4 3; 5 9 0]

b =

```    2     3     7
```
```    5     4     3
```
```    5     9     0
```

EDU>> x=A\b

x =

```   0.5000    0.3125   -0.0625
```
```   0.3125    0.5625         0
```
```   0.2500    0.3750    0.8750
```

EDU>> A*x

ans =

```    2     3     7
```
```    5     4     3
```
```    5     9     0
```

EDU>> x=b/A

x =

```   0.7500    0.2500    0.1875
```
```   0.0625    0.6250    0.2500
```
```  -0.3125    0.6250    0.5625
```

EDU>> x*A

ans =

```    2     3     7
```
```    5     4     3
```
```    5     9     0
```

EDU>> (A'\b')'

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.

EDU>> [1,2,3,4].*[1,2,3,4]

ans =

```    1     4     9    16
```

EDU>> [1,2,3,4].^2

ans =

```    1     4     9    16
```

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

EDU>> who

A ans b p x

EDU>> clear ans

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

Saving a session.

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.

EDU>> save

Saving to: matlab.mat

## Sections 5-7

% 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 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 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
```

% Flow Controls % for : 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 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
```

% 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
```

% 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 % certain functions operate on scalars, but operate element-wise when applied to a matrix % common functions include: % sin asin exp abs round % cos acos log sqrt floor % tan atan rem sign ceil % see help files for examples of these

% 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 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 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
```

% Flow Controls % for : 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 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
```

% 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
```

% 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 % certain functions operate on scalars, but operate element-wise when applied to a matrix % common functions include: % sin asin exp abs round % cos acos log sqrt floor % tan atan rem sign ceil % see help files for examples of these

## Sections 17-19

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

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

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