User:Eml4500.f08.ateam.nobrega/Homework Report One

Lecture Notes Through September 5th
Lecture Notes

What is Matlab?
MATLAB is short for "matrix laboratory". It is a program software that allows users to solve numerical problems using a programming language similar to, yet simpler and faster than, Fortran or C++. It is a matrix based system that allows for quick computation and visualization of scientific and engineering problems such as, but not limited to, plotting data and functions, implementing algorithms, solving algebraic expressions and creating programs.

An Introduction to the Matlab Primer
The MATLAB Primer Tutorial was written based on the 4.0 and 4.1 version of MATLAB. However, it can be used in updated versions of MATLAB as well. The Primer was written by Kermit Sigmon, Department of Mathematics at the University of Florida. It is designed to help one use MATLAB. It is encouraged that the Primer be used hands on with the reader sitting at their computer going through the examples. Users should type the commands into the MATLAB command window and view the MATLAB generated output for each topic.

If the user is unsure of how to perform a task or if an error message arises, he or she should call on the help function. This function can be called by typing the word help into the command window. Doing this will display a list of topics for the user to choose from. To call for a specific help topic type in the word help followed by a space and the name of the topic one is searching for. Another helpful command is to type in the word demo into the command space, allowing the user to preview some of the MATLAB functions.

The MATLAB Primer is a set of instructions for how to perform basic MATLAB functions. The MATLAB User's Guide and Reference Guide will need to be accessed for more advanced applications. To find these documents consult your instructor or visit your local library or computer lab.

"MATLAB is available for a number of environments: Sun/Apollo/VAXstation/HPworkstations, VAX, MicroVAX, Gould, PC and AT compatibles, 80386 and 80486 computers, Apple Macintosh, and several parallel machines. There is a relatively inexpensive Student Edition available from Prentice Hall publishers."

Accessing MATLAB
After logging on to a computer, the easiest way to access MATLAB is to double-click the MATLAB icon on the desktop or search for MATLAB in your program list. The MATLAB icon is featured below:



Entering Matrices
Matrices in MATLAB can be entered in several different ways. Below are two examples that output the same matrix.

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

A = 1    2     3     4     5     6     7     8     9

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

A = 1    2     3     4     5     6     7     8     9

Entering Matrices with complex numbers. Below are two different ways to enter complex matrices.

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

B =

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

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

B =

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

Referencing an element from a matrix. For example in the matrix A above, if you want to reference the value of the element located in row 2, column 3 type A(2,3). View example below.

>> A(2,3)

ans =

6

Matrix and Array Operations
MATLAB incorporates the following matrix operations: Care must be taken to ensure that sizes of the matrices are compatible or an error message will result, and the computation will not be performed."It is important to observe that these other operations, *, ^, \, and /, can be made to operate entry-wise by preceding them by a period." See the following example for further clarification.
 * Addition +
 * Subtraction –
 * Multiplication *
 * Exponential Power ^
 * Conjugate Transpose ‘
 * Left Division \
 * Right Division /

>>[6,7,8,9].*[6 7 8 9]

ans =

36   49    64    81 Notice that the operation performed was not matrix multiplication but rather an entry by entry multiplication. See the following example for matrix multiplication.

>>A=[1 2;3 4]

A =

1    2     3     4

>> B=[1 2;3 4]

B =

1    2     3     4

>> A*B

ans =

7   10    15    22

Statements, Expressions and Variables
"MATLAB is an expression language. Expressions you type are interpreted and evaluated." Examples of statement formatting:

$$variable = expression$$ or    $$expression$$

Expressions may consist of functions, operators, and names of variables. The return key executes your typed command. MATLAB is case sensitive and therefore care must be exercised when entering variable names. For example:

$$plot(x,Y) \ne plot(X, y)$$

The command "who" or "whois" displays variables currently stored in MATLAB. The command " clear variablename " deletes a specific variable.

The command "eps" prints the machine round off point useful for iterative convergence.

If a run away computation is experienced "CTRL-C" or "CTRL-BREAK" will break the calculation.

Saving the Workspace
When MATLAB is exited, all variables are lost unless previously saved. The command "save" will generate a file entitled "matlab.mat". When re-entering the program, the command "load" will reopen the saved workspace.

Matrix Building Function
Matrix building functions are

eye	       identity matrix zeros          matrix of zero ones           matrix of ones diag           create or extract diagonals triu           upper triangular part of the matrix tril           lower triangular part of the matrix rand           randomly generated matrix hilb           Hilbert Matrix magic          magic square topelitz       see help topelitz

Functions like zeros, eye, and ones can be used to create matrices. The functions are followed by the size of the matrix.

Ex:

$$>> zeros(2,3)$$ $$ans =$$ 0    0     0     0     0     0 Functions such as diagonals vectors require a vector as an input.

Ex:

$$>>A =$$ 2    2     2     2

$$>> diag(A)$$ $$ans = $$    2     2

You can combine and create new matrices using multiple functions.

Ex: This function will create a 5x5 matrix shown below.

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

$$B =$$

0    0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     1     0     0     0     0     0     1

For, While, If - and Relations
For.

Using the For. statement to produce a vector. Example for n = 3

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

or

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

Will result in:

x =

1

x =

1    4

x =

1    4     9

Producing the same vector as shown above, but in reverse order. Example is shown below.

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

x =

9

x =

9    4

x =

9    4     1

While.

A while loop allows for the statement to be executed continuosly aslong as the relation defined remains true.

General Form:

while relation statement end Example:

>> a =30; >> n = 0; >> while 2^n < a    n = n + 1; end

Will result in:

>> n

n = 5

If.

An if statement is only executed if the relation is true.

General Form:

if relation statement end

Example:

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

Relations

MATLAB Relational Operators:

MATLAB Logical Operators:

If the statement is true it is a value of 1. If the statement is false it is a value of 0. See the examples below.

>> 3 < 5

ans =

1

>> 3 > 5

ans =

0

>> 3 == 5

ans =

0

>> 3 == 3

ans =

1

>> a = rand(5)

a =

0.9501   0.7621    0.6154    0.4057    0.0579    0.2311    0.4565    0.7919    0.9355    0.3529    0.6068    0.0185    0.9218    0.9169    0.8132    0.4860    0.8214    0.7382    0.4103    0.0099    0.8913    0.4447    0.1763    0.8936    0.1389

>> b = triu(a)

b =

0.9501   0.7621    0.6154    0.4057    0.0579         0    0.4565    0.7919    0.9355    0.3529         0         0    0.9218    0.9169    0.8132         0         0         0    0.4103    0.0099         0         0         0         0    0.1389

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

Scalar Functions
MATLAB has built in functions that operate on scalars, but can also operate on individual elements of a matrix. The most common of these functions are as follows:

See the following examples:

>>sin(3*pi/2)

ans =

-1

>> log(1)

ans =

0

Vector Functions
Some MATLAB functions perform actions on vectors in a column by column fashion and produce a row vector with the results. If one wants to operate on a row by row basis, the transpose can be used.

max min sort sum prod median mean std any all

For example, to calculate on a row by row basis and find the mean:

mean(A')'

For example, the max value in a matrix B is determined by:

max(max(B))

The command example above is nested within itself. The inner most "max" function produces a single row of the max values for each column of the original matrix. The outer function produces the maximum value of these remaining row vector values.

Matrix Functions
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 cond      condition number in the 2-form rank      rank

Above is a list of matrix functions that can be used. These functions can be called using a variety of commands.

Ex:

$$Y=eig(A)$$

Or

$$eig(A)$$

Command Line Editing and Recall
Keys and their functions to edit in MATLAB

Submatrices and Colon Notaion
"Vectors and submatrices are often used in MATLAB to achieve fairly complex data manipulation effects. "Colon notation" ( which is used both to generate vectors and reference submatrices) and subscripting by integral vectors are keys to effcient manipulation of these objects." A row vector of length n may be defined as 1:n where n represents the length of the vector. The default increment is taken to be 1 unless otherwise specified. See the following examples for further clarification. A row vector of length n may be defined as 1:n where n represents the length of the vector. The default increment is taken to be 1 unless otherwise specified. See the following examples for further clarification.

>>1:5

ans =

1    2     3     4     5

>> 1:2:5

ans =

1    3     5 Both vectors are row vectors from 1 to 5, but the second vector is from 1 to 5 with an increment of 2."

Colon Notation" may also be used to access submatrices of a matrix, and to replace elements within matrices. See the following example for further clarification.

>>A =

1    2     3     4     5     6     7     8     9    10    11    12    13    14    15    16

>> A(1:2,3)

ans =

3    7 This creates a column vector consisting of the first 2 entries of the 3rd column of matrix A.

M-files
M-files are a specific type of file MATLAB is capable of executing. A M-file consists of a series of sequential commands and are characterized by the ".m" file extension. MATLAB M-files fall into two categories: script files and function files.

Script Files
Script files are composed of normal MATLAB commands. To execute the commands inside of a script file, simply type the file name. For example, if the file name is "transpose.m", the command "transpose" will execute all the statements to be performed.

Details of script files:
 * 1) Can reference other M-files or itself
 * 2) Variables are global and will overwrite current session variables
 * 3) Useful to avoid repetitious data entry

To create a .m script file, simply use the built in editor of MATLAB and save the file with a .m extension. For example if the following M-file entitled "test.m" was executed by using the command "test":

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

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

C=A+B

The current workspace will now have three variables imported into memory: A, B, and the result, C.

Function Files
The second type of M-file is the function file. This tool extends the convenience of built in functions but allows for customization to specific tasks. Note that variables in a function file are local by default. See the following example from the MATLAB Primer document.

function a = randint(m,n) %RANDINT Randomly generated integral matrix. % randint(m,n) returns an m-by-n such matrix with entries % between 0 and 9 a = floor(10*rand(m,n));

Note the following procedures when creating a function file:
 * 1) First line must begin with "function" and define the input variables
 * 2) "%"-Allows for comments
 * 3) Last line defines output variables

As an example to run the above program, "k = randint(4,3)" could be used.

This command passes 4 and 3 to the program and stores the result in a new matrix, k. Note that variable names are not carried over outside of the function M-file.

Text Strings, Error Message, Input
Text strings can be entered into Matlab using single quotations. These strings can be displayed by using the disp command.

Ex: s= ‘peter pan had an accident’

disp(‘peter pan had an accident’)

Error messages that are placed in M-files can abort the program.

Ex:

error(‘Sorry, this matrix is wrong’)

Strings can also be added into an M-file to make the program interactive.

Ex:

iter = input(‘Enter the number of times you want to enter a number:’)

Managing M-Files
It is recommended that if your system allows you to run multiple processes that you keep both the MATLAB Command Window and your m-file editor open simultaneously. At any point if you would like to edit your m-file use the function !ed. For example you would type into the command window as follows: >>!ed filename.m

Note: Make sure to replace filename with the file you are trying to edit.

Commands useful for managing m-files.

Comparing Efficency of Algorithms Flops, Tic and Toc
Older versions of MATLAB had the function flops which kept a running total of flops performed to solve and algorithm. In more resent versions of MATLAB the command function flops is unavailable and an error message will appear if the command is entered. The command function “tic, any statement, toc” can be used to obtain the elapsed time (in seconds) it takes MATLAB to solve the algorithm. This enables the user to compare the efficiency of his / her algorithms. See the example below for further explanation.

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

A =

1    2     3     7     8     9     4     5     6

>> b= [1 2; 4 5; 8 9]

b =

1    2     4     5     8     9 >> x=A*b

x =

33   39   111   135    72    87 >> tic, x=A*b; toc

Elapsed time is 0.000000 seconds.

Output Format
MATLAB calculations are performed in double precision. However, output formatting can be changed with the following commands:

format short      fixed point with 4 decimal places (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

Hardcopy
The easiest way to safe your command file in Matlab is the diary command. The diary command, when followed by a file name will save the data under the new name. However if no file name is provided, the file will be saved under a generic name of diary. The file can be opened later for further editing or printing.

$$diary$$ $$filename$$

Planar Plots
The plot command creates linear x-y plots; if x and y are vectors of the same length, the command plot(x,y) opens a graphics window and draws an x-y plot of the elements of the x versus the elements of y.

For example command: >> x = -4:.01:4; y=sin(x); plot(x,y)

Results in:

One can also refrence a function from an m-file in the given format: >>fplot('expnormal',[-1.5,1.5])

Results in:

Plots of parametrically defined curves can also be made. For example:

Commands for plots:

Manualing Scaling Axes:

Multiple Plots on a Single Graph: Two possible ways

1. Example: Listing them within the same command line >> x=0:.01:2*pi; Y=[sin(x)', sin(2*x)', sin(4*x)']; plot(x,Y)

Result in:

2. Example: Using the hold function >> x=0:1:10; y=x; plot(x,y) >> hold on >> x=0:1:10; y=2*x; plot(x,y) >> x=0:1:10; y=3*x; plot(x,y) >> hold off

Result in:

Editing Linetypes, Marktypes, and Colors of plots:

Commands:


 * Linetypes: solid(-), dashed(--), dotted, dashdot(-.)
 * Marktypes: point(.), plus(+), star(*), circle(o), x-marks(x)
 * Colors: yellow(y), magenta(m), cyan(c), red(r), green(g), blue(b), white(w), black(k)

Example Code: >> x=0:.01:2*pi; y1=sin(x); y2=sin(2*x); y3=sin(4*x); plot(x,y1,'--',x,y2,':',x,y3,'+')

Graphics Hardcopy
To obtain a hardcopy of your plots you would use the commmand: >>print

3-D Line Plots
To plot a 3-D line defined by vectors x, y, z of the same size, you would use the command plot3(x,y,z). Below is an example:

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

Result in:

3-D Mesh and Surface Plots
3-D Surface Mesh plots are drawn with the command mesh

Example Code:

>> mesh(eye(10))

Result in:

Faceted surface plots are drawn with the command surf

Example Code:

>> surf(eye(10))

Result in:

Plotting 3-D Functions: Function:



Code:

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

Resulting in:

One could also use the surf command for the same function resulting in: Code:

>> surf(z)

Shading and Color Profiles

Commands:

*shading faceted *shading interp *shading flat

*colormap(hsv) Note: Default *colormap(hot) *colormap(cool) *colormap(jet) *colormap(pink) *colormap(copper) *colormap(flag)

Other Useful Commands: Can further explore under the help command

*meshz *surfc *surfl *contour *pcolor

*colormap(gray) *colormap(bone)

Sparse Matrix Computations
A great deal on computation time and memory storage space can saved when performing calculations on a matrix that has many zero entries by using the command sparse. “Matlab has two storage modes, full and sparse with full the default. The functions full and sparse convert between the two modes.” "A sparse matrix is stored as a linear array of it’s nonzero elements along with their row and column indices.” See the following example for further explanation.

F =

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

>> S=sparse(F)

S =

(1,1)       9   (2,1)        2   (1,2)        4   (3,2)        8   (2,3)        7   (3,3)        1   (4,3)        4   (4,4)        3   (5,4)        8   (4,5)        6   (5,5)        2   (6,5)        1   (5,6)        4   (6,6)        4

>> F=full(S)

F =

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

The command S=sparse(F) creates the sparse matrix S from the matrix F, and the command F=full(S) returns matrix F back to its original form.

Contributing Team Members
The list below is in no particular order.

Pedro Rivero User:Eml4500.f08.ateam.rivero 18:14, 17 September 2008 (UTC)

Akash Shah Eml4500.f08.ateam.shah 14:49, 18 September 2008 (UTC)

Tatiana Nobrega User:Eml4500.f08.ateam.nobrega 23:03, 18 September 2008 (UTC)

Michael Carr Eml4500.f08.ateam.carr 23:13, 18 September 2008 (UTC)

Taylor Boggs Eml4500.f08.ateam.boggs.t 04:34, 19 September 2008 (UTC)

Josh McNally Eml4500.f08.ateam.mcnally 03:41, 19 September 2008 (UTC)