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

Matlab Primer
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:
Output:
Input:
Output:
Complex numbers also have multiple ways of entering them into MATLAB. The following code demonstrates two approaches.
Input:
Output:
Input:
Output:
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.
Input:
Output:
Input:
Output:
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:
Output:
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:
Output:
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:
Output:

## 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:
Output:
Input:
Output:
Input:
Output:
Input:
Output:
Input:
Output:
Input:
Output:
Input:
Output:
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:
Output:
Input:
Output:

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

## 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:
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:
Matrices can be built from blocks; if A is a 3-by-3 matrix, then

## Loops, if statements, and relations
### For Loop

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

### If Statement

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

### 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.
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:
Common MATLAB Functions :
| sin | asin | exp | abs | round |
| cos | acos | log | sqrt | floor |
| tan | atan | rem | sign | ceil |
* 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:
MATLAB Vector Functions :
| max | sum | median | any |
| min | prod | mean | all |
| sort | std | | |
Example:

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

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

## 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
creates the output line vector
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:
is the column vector of the first three entries of the fourth column.
is the entire fourth column.
is columns 2 and 4 of A.
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,
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,
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,
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,

## 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:
Table 14.1 MATLAB Commands related to M-files :
| Command | Description |
| path | Displays a list of all active MATLAB directory search paths |
| pwd | returns the name of the active working directory |
| cd | Used to change the working directory |
| dir or lis | Lists the contents of the active directory |
| what | Lists only the M-files in the directory |
| delete or type | Used to delete a diskfile and print an M-file to the screen |

## 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 flops(0) resets the flops to zero and is normally entered prior to running a an algorithm. Entering the flops 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 flops command can no longer be used. MATLAB will display the following error:
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 tic and toc. For example, to find the total time needed to solve the equation K=f*d, 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:
Table 16.1 Output Display Commands :
| Command | Output Display |
| Format short | Fixed point with 4 decimal places (the default) |
| Format long | Fixed point with 14 decimal places |
| Format short e | Scientific notation with 4 decimal places |
| Format long e | Scientific notation with 15 decimal places |
| Format rat | approximation by ratio of small integers |
| Format hex | Hexadecimal format |
| Format bank | Fixed dollars and cents |
| Format + | +,-,blank |
Once introduced, the chosen format will remain in effect until changed.
The command format compact will suppress blank line allowing more information to be seen on the screen.
The command format loose 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.
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,
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.
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.
This same feature can be done by creating a Y matrix and then plotting that matrix with respect to x.
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.
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.
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.
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.

## 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.
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.
Another way to enter in a sparse matrix is to only enter in the non-zero elements. Example code for this is shown below.
Operations can by applied to any matrix regardless if it is sparse or full.