User:Eml4500.f08.gravy.jad/Matlab2

 Summery of Matlab tutorial by Kermit Sigmon 

Accessing MATLAB
After MATLAB is installed to the computer, it may be accessed either by clicking on a icon on the desktop, or if that icon was not created, by selecting the icon in the start menu. An alternate method to access MATLAB is to enter it into the system command which can also be found in the start menu

For convenience, MATLAB, as well as the local editor should both remain open in separate windows for any computer system that allows for multiple processes. Any questions in this area should be directed towards the computer manufacturer.

Entering Matrices
Matrices are the method by which MATLAB represents all variables. Single variables or interpreted as a 1 x 1 matrix, with no indicated direction. This is also known as a scalar quantity. A vector is represented by any matrix consisting of one column, or one row. All matrices are two dimensional and must consist of numerical values.

There are multiple methods by which to introduce a matrix into MATLAB including loading the matrix from a disk or file, inserting the matrix manually, or using a matrix that has been generated by another mathematical equation. The following two statements are examples of the correct syntax to generate a 3 x 3 matrix:

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

A= [

1 2 3 4 5 6 7 8 9]

The first example separates the values by spaces and the rows by semi-colons while the second separates the rows by lines.

To indicate an exponent, values must be entered in without spaces (i.e. 2.34e-5) for proper syntax. MATLAB also has the ability to interpret imaginary numbers using i and j. These values are also entered without spaces (i.e. 3+4i). If the values of i and j are assigned prior to their use as an imaginary value, a new value can be used by first setting it equal to the square root of negative one.

If a matrix is too long and tedious to enter manually it should be entered via an ASCII file from the local editor to avoid possible error from input. To load files in MATLAB, use the load command followed by the name of the file.

For example: load filename.ext If a user wishes to experiment with matrices of random numbers the rand, magic, and hilb functions provide a solution. The rand function creates a matrix of randomly generated numbers for a matrix with the same number of rows as columns. The magic function creates a magic square matrix. This is a particular type of matrix where the rows, columns, and diagonals have a common sum. The hilb function creates a Hilbert matrix.

Matrix and Array Operations
MATLAB has a variety of operations available including addition (+), subtraction (-), multiplication (*), power (^), conjugate transpose (‘), left division (\), and right division (/) all of which can be applied to both scalars and vectors. Order of operations applies.

Statements Expressions and Variables
Matlab uses operators, functions and variable names (which are case-sensitive) to complete tasks. When an operation has been completed the results are displayed in matrix form, unless the line ends in a semicolon. The semicolon will suppress the output but the operation will still be carried out. To stop matlab mid operation hit CTRL and C, or CTRL and break.

The workspace saves all variables and their values. The command “who” or “whos” will displace the variables in the workspace. To clear a variable the command is “clear” followed by the variable name, if the variable name is omitted then all variables will be cleared.

Saving a Session
To save the variables from the workspace the command is “save”. Save will write the variable in a file called matlab.mat. To load the saved session the command is “load”.

Matrix Building Functions
Some commonly used functions in Matlab consists of:

For example, by saying zeros(m,n) produces an mxn matrix containing zeros. By saying zeros(n) produces an nxn matrix containing zeros. By saying zeros(A) while A is an existing matrix, it produces a matrix size A containing zeros.

For, if, while -and relations
For, if and while are different types of loops used in Matlab.

for:

-The "for" loop produces a vector of size "n" for a given function "x"

-saying, i=n:-1:1, will write the vector backwards

-There can be double nested "for" loops (two or more for loops in the same loop. This will produce an mxn matrix.

-A matrix can be used instead of "n" and it will assume to compute the matrix

while:

-The "while" function is a loop that will continue to loop until the condition statement becomes false

if:

-The"if" function is a single loop that will only enter the loop if the primary condition is met

-it is a single loop

Relations

Some common relational operators used in Matlab consists of:

logical operators are as follows:

In addition, any true/false relations appear as a scalar number 1/0.

Scalar Functions
There are some functions in MATLAB that were designed and created for scalar functions. These functions can still operate element-wise on matrices. Some common examples are sin, cos, tan, asin, acos, atan, exp, log, ln, rem (remainder), abs (absolute value), sqrt (square root)

Vector Functions
Unlike scalar functions, vector functions are, as their name hints, used on vectors (i.e. matrices or size m x n). These functions when used yield answers which are also in vector form. Some common examples of vector functions are max (max value), min (min value), sort (sort values), median, mean, std (standard deviation), sum, prod (product)

Matrix Functions
As mentioned above, matrices are used as a representation of variables in MATLAB. This is what makes the program such a useful tool. Some common examples of matrix functions are eig (eigenvalues), chol (choleski factorization), inv (inverse), hess (hessenberg form), det (determinant)

Command line editing and recall
- editing is easy -> backspace or delete to the right or left of the cursor

- commands: Ctl-a, Ctl-e, Ctl-d, Ctl-k for Unix or PC systems

- the cursor can be moved up or down to recall any previous line, therefore one can move the cursors up, down, left, right and recall and/or edit anything on the page

Submatrices and colon notation
-matlab uses vectors and submatrices, often generated by "colon notation"

- "colon notation" and subscripting is used to manipulate data sets

- ex: A(1:4,3) = matrix A, column 3, elements 1 through 4

A(:,3) = matrix A, column 3, all elements

A(:,[2 4]) = matrix A, column 2 and 4, all elements

M-Files
M-files M-files are are stored files usually ending with the “.m” extension. They allow MATLAB to run an entire preprogrammed series of commands. They effectivly make up the backbone of MATLAB, and most work is usually done to create or edit these files. There are two main types of m-files: script files and function files.

Script Files Script files are a type of m-file that contains a sequence or normal MATLAB commands. They are normally used for the creation and mataince of large variables, such as matrices. The varibable created in a script file are global. To call a script file, simply enter a command into MATLAB that is the name of the script file with the “.m” extension left off. For example, if the file is named “example1.m” than typing in the command “example1” will cause the script file to run.

Function Files Function files are the true brains behind MATLAB. They allow for the creation of any type of function programmable, which greatly extends the cabalities of MATLAB. Function files, unlike script files, default to creating local variables. However they can be declared global if the need arises. A function files starts with the line “function variable=execute(a,b)”. The word “function” tells MATLAb that the following is a function. “variable” is the output argument, and the name can be changed to be more descriptive. “execute(a,b)” is the name of the function (execute) and the variables that need to be passed into the function (a,b). The list of variables (a,b), called the input arguments, can be expanded or deleted to fit the need of the function. Function files, like all m-files, are able to use and call other files within them, allowing for a greater range of programming options.

An example of a function file is shown below. Remember that the “%” symbol allows for comments without affecting any code. MATLAB ignores all statements after the % symbol.

function a=randint(m,n) %RANDINT Randomly generated integral matrix. %       randint(m,n) returns an m-by-n matrix with entries

%      between 0 and 9 a=floor(10*rand(m,n))

Putting the command “z=randint(3,6)” into MATLAB will return a 3-by-6 matrix variable named “z”. The great advantage to function files is the ability to expand and create huge programs. This allows for the creation of many smaller function, similar to the randint(a,b) created before, to be combined into a large file that can be programmed to do thousands of different things. Also, there is the ability to combine self-made functions with some of MATLAB’s built-in functions, much like the built in function “rand(x,y)” was used above.

A useful command to find out a list of all the functions that MATLAB has access to, a combination of built-in and user programmed functions, can be seen by typing the command “type functionname”.

Text strings, error messages, input
To enter a text string in MATLAB, use single quotes: s = 'This is a test' This will assign the text string ‘This is a test’ to the variable s.

To display a text string, use the function disp: disp('this message is hereby displayed');

To display an error message, use the function error: error('Sorry, the matrix must be symmetric'); This also will exit the M-file upon execution.

To prompt the user for input data, use the function input: iter = input('Enter the number of iterations: '); This will display ‘Enter the number of iterations’ and pause execution while the user inputs the data which is then data assigned to the variable iter.

Managing M-files
To keep MATLAB active while editing a file in order to avoid losing all variables, use the !-feature by inserting a ! before any system command: >> !ed rotate.m This will let you edit rotate.m using the local editor without exiting MATLAB.

See help dbtype and references given there for more concerning debbugging tools.

The following commands will duplicate system commands without the use of a !:

M-files must be in an accessible directory. Storing personal M-files in a subdirectory named Matlab in one’s home directory should work. For further information see the discussion of MATLABPATH in the User's Guide.

Comparing efficiency of algorithms: flops, tic, toc
There are two measure of algorithm efficiency: floating point operations (flops) performed and the elapsed time (tic and toc).

The MATLAB function flops keeps a running total of the flops performed.

To reset the flops count to 0, use the command fops(0), not flops=0. Do this at the beginning of the code, and then use the command fops at the end to get the fops count of the algorithm: fops (0); x=A\b; fops

The MATLAB functions tic and toc give the elapsed time between the two commands: tic; x=A\b; toc

However, on timesharing machines, elapsed time is not as reliable as flops at determining algorithm efficiency because the rate of execution is dependent on how busy the computer is at the time.

Output format
To control the format of the displayed output, use the following commands:

Once invoked, the chosen format remains in effect until changed.

To suppress most blank lines, use the command format compact. To reverse the format compact command, use format loose. These are independent of the other format commands.

Hard copy
Saving input from the command window to an alterable and printable file can be done using the command diary. To start recording the command is “diary” then the file name. If you don’t give a file name the default file name is diary. To end recording the command is “diary off”.

Planer plots
The command for plot is “plot (x,y)” with x and y being the variables to be plotted. An interval and mesh size can be set by “variable name= lower limit: mesh size: upper limit”.

“fplot (‘function file’,[lower limit, upper limit])” is the command to graph functions. Function file is a m-file that contains the function to be graphed.

Only one figure is active at a time but you can switch between the figures using “figure(n)” where n is the figure number wanted. “gcf” command gives the active figure’s number.

Multiple plots on one graph can be made using “plot(x, y1,x,y2,…)”Other ways are, declaring a matrix of functions like U=[function1, function2 ] and using plot(x,U). Or using the “hold” command to freeze the current plot and all plots after will be placed on the same plot. To unfreeze the plots, the command is  “hold off”.

3-D line plots
To create 3-d plots the command is “plot3(x,y,z)”.

3-D mesh and surface plots
To create 3-D wire mesh surface plots the command is “mesh(z)” and three dimensional faceted surface plots “surf(z)”where z is a matrix of points in the z direction.

To plot a function over a rectangle use first the command “[x,y]=meshgrid(xx,yy)” where xx and yy are matrices of the sides of the rectangle. x and y result in matrices whose columns equal xx and yy respectably. Next the command mesh is used with z= exp(-x.^2-y.^2)

The color of the shadings can be changed using the command “shading” followed by the setting. The settings are faceted, interp ( for interpolated), and flat. The color profile is changed using the command “colormap” followed by the color. The color codes are hsv, hot, cool, jet, pink, copper, flag, gray, and   bone.

Labeling the figure
The commands Title, xlabel, ylabel and zlabel, can be used to label the figure. An example is Title(‘Title name’).

gtext(‘The Spot’), command places text where on the figure the mouse is clicked, while the text command places the text at coordinates.

Axis scaling
The following commands are used to change the scaling on the axis.

axis([x lower limit, x upper limit, y lower limit, y upper limit ]), to set scaling.

axis(axis), freezes scaling for subsequent graphs.

axis auto, resets the scale to the default.

Variable= axis, the variable will be set to the current scaling.

axis square, makes the same scale for both axes.

axis equal, make the same scale and tic marks for both axes.

axis off, turns off scaling and tic marks axis on turns them on.

Line types
To change the line type, mark type and color use the tables below. The syntax is Plot(x,y,’color line type mark type’) so Plot(x,y,’b:*’) is a blue dotted line with star markers.

'''

Graphics hard copy
The command “print” will send the current graphic to the default printer. The command “print ” then the file name will save and overwrite the graphic to a file, but ”print -append” then the file name will add the graphic to the end  of a file.

To save a graphic that is not the current one, the command is “print –deps –f#” then the filename and # the figure number.

Sparse Matrix Computations
There are two storage modes in Matlab for a matrix: full and sparse. Full mode stores everything, while sparse only stores nonzero numbers. The default is to store elements of a matrix in full mode. In full mode, the zero elements are taken into account during calculations. Sparse mode will remove these zero elements during calculations, thus reducing time spent performing them. It saves time, but still outputs the same numbers.

Matrices can be converted between sparse and full fairly easily. The command “S=sparse(F)” will convert the full matrix, F, to a sparse matrix, S. It can then be converted back from sparse to full using the command "F=full(S)”. Usually though, if a sparse matrix is desired, it will be created directly rather than by converting from a full matrix. There are sparse analogs to many full matrices. The functions speye, sparse, spones, and sprandn are sparse analogs to the full functions eye, zeros, ones and randn respectively.

When performing calculations using both full and sparse matrices, the storage mode of the output will vary. If calculations are performed on only sparse functions, the output will be sparse. If calculations are performed only on full functions, the output will be full. However, if calculations are performed using both full and sparse functions, the output will always come out as full unless the user specifically states otherwise.