User:EML4500.f08.JAMAMA/MatlabTutorial1

To go back to Homework Postings:

To go back to Team JAMAMA's Home Page:

Accessing MATLAB

 * On most systems one can enter Matlab with the command matlab, although on other systems you can access it through a menu or just by clicking an icon.

Entering Matrices

 * Matlab mainly works with a rectangular numerical matrix. All variables represent matrices.

Imaginary numbers can also be entered, using the units i or j.


 * Large amounts of data can easily be loaded using the command load data.ext, where .ext could be any extension. The best files to use are ASCII files.
 * To just create matrices one can just use some of the built in functions.

Individual parts of matrices can be referenced simply by their address. so A(2,3) will select the entry in matrix A, row 2, column 3.

Matrix Operations, Array Operations

 * If the sizes of the matrices your trying to operations on do not coincide with one another an error message will appear, that is unless one of the matrices is a scalar (a 1X1 matrix). A scalar can be used on any size matrix.
 * Also, the division operators are related to one another. Right division is defined in terms of left division by b/A = (A'\b')'.

Matrix operations, array operations

Array Operations

Although addition and subtraction only operate entry-wise, the other operations are matrix operations. Entry-wise will operate on each of the individual elements, while matrix operations operate on the matrices as a whole.

Matrix operations, array operations

Statements, expressions, and variables; saving a session

 * Matlab statements are usually in the simple form of expressions, which are typically composed of operators functions and variable names. When an expression is evaluated it is turned into a matrix with a variable as its name.  If no variable is assigned, a variable ans is created to store that particular matrix.
 * Statements end by pressing enter. They can be continued by putting three or more periods then pressing enter, or can simply be put on one line (but they must be separated by comas or semi-colons).
 * Putting a semicolon at the end of a line makes it so the operation is still done, yet it is not immediately printed.
 * Matlab is case sensitive; A is different than a.
 * The command Who will list all current variables.
 * The command clear can be used before a variable to just delete that one, or used on its own to delete all variables.
 * The permanent variable epsilon (eps) rounds to about 10^-16 on most machines which can be used for converging iterative processes.
 * To stop an unwanted computation without leaving matlab press CTRL-C.

Saving a Session One can hit the save button to store a session as a diskfile with the extension .mat. You can then re-enter Matlab later and use the load function to restore the former workspace.

Matlab Homework Assignment Code 

Matrix Operations, Array operations
If sizes of matrices are incompatible with the operator, and error message is shown. The matrix division operators required extra attention. If A is an invertible square matrix and b is a compatible column, resp. row, vector, then

x=A\b is the solution of A*x=b and resp.,

x=b/A is the solution of x*A=b

Array Operations

The matrix operators of addition and subtraction will work for arrays but the other operators will not. The matix operators can be used to operate entry-wise by placing a period in front of the operator.

Statements, expressions, variables
MATLAB is an expression language where exspression are comprised of operators, functions,and variable names. Expressions are evaluated into matrices and stored as such. Statements are generally terminated with a carriage return but can be continued onto the next line. Also statements can be terminated with a semicolon or period, which suppresses printing of the statement but still carries out the operation. MATLAB is case sensitive. Runaway displays or computation can be halted with CTRL-C.

Saving a session

All variable are lsot when MATLAB is close. Using the save command saves the variables to a .mat file which can later be retrieved with the load command.

Matrix building functions
Some functions in matlab will accomplish predetermined convinient tasks for you.

Here is an example of the of a 5-by-5 matrix(B) created from an original 3-by-3 matrix(A):

disp('5. Matrix Building Function.')

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

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

The result in MatLab is:

5. Matrix Building Function.

A =


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

B =


 * 1    2     3     0     0
 * 4    5     6     0     0
 * 7    8     9     0     0
 * 0    0     0     1     0
 * 0    0     0     0     1

For, while, if and relations
For

For a given n, the statement

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

will produce a certain n-vector and the statement

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

will produce the same vector in reverse order.

The for statement permits any matrix to be used instead of 1:n.

While

The general form of a while loop is

while relation

statements

end

The statements will be repeated as long as the relation remains true. For example, for a number a, the following will compute the smallest non-negative integer n such that 2^n>a:

n=0;

while 2^n < a

n = n + 1;

end

n

If

The general for of an if statement is

if ''relations

statements''

end

The statement will only be executed if the relation is true. The if function can be branched using the elseif and else functions. For example:

if n < 0

parity = 0;

elseif rem(n,2) == 0

parity = 2;

else

parity = 1;

end

Relations

Many of the relational operators used in MATLAB are used very similar to the operators used in C++ to compare variables. The advantage to using MATLAB for relational operators is when matrices are being used. In a programming language you would need to write a for loop when comparing matrices instead of just a single line of code.

When using these statements, the line of code will return a 0 or 1 representing false and true respectively.

Scalar Functions
Many functions in MATLAB use matrices but some operate on each element in the matrix called scalar functions.

Vector Functions
Vector functions in MATLAB operate on each column of the matrix. So if A is a 3X3 matrix min(A) would return a 1X3 matrix with each value the minimum of their column. If the matrix is only one row but multiple columns such as the return from the min(A) function, the minimum of the row is found and returned by the function. So if the user wanted to find the minimum of a matrix, min(min(a)) should be used so the matrix can be of any size and the desired effect is achieved.

Matrix Functions
MATLAB's most powerful feature is its matrix functions.

Submatrices and Colon Notation
Matrices can be formed by using colon notation instead of writing out the whole matrix. Also a portion of a matrix can be created into its own matrix by using submatrices.

M files
Script Files

Script files consist of normal MATLAB commands in an m-file. To run a script in the working directory in MATLAB, simply type the name of the m-file and all of the lines in the script file will be run.

Function Files
This allows users to create their own custom functions in MATLAB if the existing functions are not enough or if the user would like to modularize their MATLAB program. All variables are local by default (only seen within the function) but can be made global (able to be seen by all functions) by using the global command.

Text string, error messages, and input

In MATLAB variables can be set to string values using single quotes. Also, display messages and error messages for MATLAB programs use the same way of defining string values. Input from users can also be taken in string format and saved in a string type variable.

Managing M-files

Comparing the efficiency of algorithms in MATLAB

When using MATLAB there are many different ways to get to the same result in your program. The program can be made more efficient by changing the way a certain operation is completed for the faster and more efficient way. This can be discovered using flops and the tic toc feature.

Output Format

All of the calculations in MATLAB are done in double precision, but sometimes for certain programs the data needs to be formatted. For instance, if the value returned be a function is an amount of money it only makes sense to show it as 2 decimal places.

Hardcopy

The list of commands can be written to a file using the diary command. Diary can be turned off by typing diary off and then typing diary on when done.

Graphics
MATLAB can make many different graphs and plots including planar plots, 3d line plots, and 3d mesh plots.

Planar plots

Planar plots are the traditional x-y cartesian plotting. In MATLAB this is done by setting a range and interval of point for the x values and the function for the y values. The plot is then created with the plot(x,y) command.

Titles and labels can be added using graph commands.

Axes are automatically set but can be overwritten by using axis commands.

Multiple graphs can be displayed on the same graph using the plot command

MATLAB can also change the style of the line plotted to allow for easier reading of graphs with multiple lines.

3D Line Plots
3-dimensional line plots are extremely similar to the plots previously described for 2-dimensional coordinate systems. The command used to produce a 3D plot is "plot3"; it produces curves in 3D space. If the defined vectors are labeled x, y, and z, then the command would appear as follows: "plot(x, y, z)".

try it

Similar to planar plots, titles and axis labels, the command "axis", may still be used. However, the command "zlabel" needs to be included in order to label the z-axis. Take note, that the "axis" command now requires a 6-vector in order to set the axis scaling to any prescribed limits.

3D Mesh and Surface Plots
The "mesh" command allows the user to plot 3D wire mesh surface plots. "Mesh(z)" draws the 3D perspective plot for the elements in a prescribed matrix z.

In order to graph a 3D surface plot, the program reads the command "surf(z)".

In order to graph a function $$z = f(x,y)$$, over a rectangle, the vectors $$xx$$ and $$yy$$ need to be defined. They provide the partitions of the sides of the rectangle. For the function "meshgrid", matrices 'x' and 'y' must be defined. For matrix 'x', each row equals xx, and the column length equals $$yy$$. For matrix 'y', each column equals $$yy$$.

[x,y] = meshgrid(xx,yy);

In order to compute the matrix 'z', $$f$$ must be evaluated entrywise over the 'x' and 'y' matrices. "Mesh(z)" or "surf(z)" may be used at this point.

In order to provide color to the surfaces, utilize the "shading" command. The three available options are as follows: "faceted", which is the default shading option, "interpolated", and "flat". These words must be integrated into a full command as follows: "shading faceted", "shading interp", or "shading flat".


 * NOTE: If the command "surf" is used, either of the commands "interpolated" or "flat" will remove all mesh lines.

To change the colors of the different shading options, use the "colormap" command. The options available for "colormap" are as follows: "hsv", which is the default, "hot", "cool", "jet", "pink", "copper", "flag", "gray", and "bone".

If the coordinate system needs to be changed to either cartesian or polar coordinates, the command "view" would be used. This changes the viewpoint from which the 3D object will be seen.

Geometrically defined surfaces can be drawn as well. "Sphere" and "cylinder" are used to generate plots of named surfaces.

 Sparse Matrix Computations

MATLAB always automatically assumes that within any matrix, that any one of the elements may be nonzero. If multiple zeroes do exist, time and memory can be saved by using sparse matrices. If there is a matrix 'A', "nnz(A)" will return only the number of nonzero elements included within that matrix.

By specifying diagonals, a sparse banded matrix can be created rather effortlessly with the usage of the function "spdiags".

Contributing Team Members
Megan Alvarez --EML4500.f08.jamama.megan 23:56, 16 September 2008 (UTC)

William Mueller --Eml4500.f08.jamama.mueller 19:07, 19 September 2008 (UTC)

Justin McIntire --Eml4500.f08.jamama.justin 19:11, 19 September 2008 (UTC)

Arunas Janulevicius --Eml4500.f08.jamama.jan 19:51, 19 September 2008 (UTC)

Chris Alford --Eml4500.f08.jamama.chris 19:54, 19 September 2008 (UTC)

Cedric Adam--Eml4500.f08.jamama.adam 19:59, 19 September 2008 (UTC)