User:Eml4500.f08.wiki1.aguilar/hw1

Section 1 How to Access MATLAB
After logging onto a computer with MATLAB installed, run the system command matlab or click on the desktop icon. To exit MATLAB, enter quit or exit in the MATLAB command window, or click on the File menu and select Exit MATLAB.

When the Editor in MATLAB is opened, it is convenient to have the Editor and Command windows opened separately. The specifics of the Editor are covered later on in this tutorial.

Section 2 Entering Matrices
MATLAB is based around operating with matrices. In fact, MATLAB is an abbreviation for Matrix Laboratory. The program can interpret these matrices as either scalars or vectors.

Matrices can be created by entering an explicit list of elements, generating built in statements and functions, creating a disk file with a local editor, or loading external data files or applications.

The following are all examples for creating matrix A, which is a 3x3 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]

Notice that the elements in the rows of the matrix can be separated by commas or blank spaces.

The following is an example of how to enter a number in exponential form.

x = 2.34e-9

Notice when the number in entered, there are no spaces in between the e.

MATLAB is capable of doing computations with complex numbers. The following are examples of how to create complex matrices.

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

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

Notice when the complex numbers were listed inside the matrix, no blank spaces were used. It should also be noted that either i or j can be used as the imaginary unit. Also, if i or j are assigned as variables to represent a new value, they will not retain their value as an imaginary number. For example if the user enters the command

i = 5

then i will no longer be equal to 'sqrt(-1)', it will be equal to 5.

If a large matrix must be entered, creating an ASCII file is a good option because it can make it easier to correct errors. If an ASCII file is created and named data.ext, simply type load data.ext into the MATLAB command line and press enter. This command will read the file and save it as the variable data. MATLAB also has built in functions such as rand, magic, and hilb. If rand(n) is typed into the command line, MATLAB will create a n x n matrix with randomly generated numbers distributed uniformly between 0 and 1. If rand(m,n) is typed into the command line, MATLAB will create a m x n matrix with the same criteria as before. If magic(n) is typed into the command line, MATLAB will create an integral n x n matrix which is a magic square. This means all the rows, columns, and diagonals have a common sum. If hilb(n) is typed into the command line, MATLAB will create a n x n Hilbert matrix.

Individual entries in a matrix can be easily referenced. For example,

A(2,3)

selects the value in the second row, third column of matrix A. Also

X(3)

Would select the third coordinate of vector X.

Section 3 Matrix and Array Operations
The following matrix operations are available in MATLAB:

+	addition -	Subtraction ^	power ‘	conjugate transpose \	left division /	right division
 * multiplication

Since a scalar value entered into MATLAB is stored as a 1 x 1 matrix, these operations also apply to those values. If MATLAB is told to perform an operation that is not possible for a specific matrix, an error message will appear on the screen.

Matrix division can sometimes be confusing in MATLAB. The difference in right and left division is shown below.

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

x = b/A is the solution of x*A = b (another way of writing this could be x = (A’\b’)’ )

It is also important to note that addition and subtraction operate entry wise, but multiplication, power, and left and right division operate as matrix operations. These matrix operations can operate as entry wise operations by placing a period in front of them. An example is

[1,2,3,4].*[1,2,3,4]	or 	[1,2,3,4].^2

Both of these operations will give [1,4,9,16] as the solution.

Section 4 Statements, Expressions, and Variables and Saving Sessions
MATLAB uses expression language. This means when values are typed in, they are entered in the form of variable = expression or just as expression. For example,

x = 5*4

The evaluation of this expression is created as a matrix and displayed on the screen, such as

x = 20

If a variable and equal sign are not used, the result is automatically saved as the variable ans.

The user can also decide to continue the statement to the next line by using three or more periods (…) followed by enter, or several statements can be placed on a single line by separating them with commas (,) or semicolons (;).

If the variable is rather large, it may be useful to suppress the statement. By placing a semicolon (;) at the end of a statement, the assignment is carried out, but the result will not be printed on the screen.

It is also important to note that MATLAB is not case sensitive. For example, alpha is not the same as Alpha.

In order to see a list of variables that are currently being used in the workspace, type who (or whos) in the command line. If a variable needs to be cleared from the workspace, enter clear variablename'. If clear is entered into the command line, all nonpermanent variables will be cleared.

If the unit round off needs to be changed, type in eps (epsilon) to have MATLAB use a round off of 10^-16. This can be useful in specifying tolerances for convergence of iterative processes.

Sometimes a computer will enter a loop that does not stop or takes too long to calculate. These computations can be stopped in MATLAB by pressing CTRL-c.

When MATLAB is closed, all of the variables in the workspace are deleted. If these variables need to be saved, enter save in the command line before closing the program. These variables are written to a disk file named matlab.mat. When MATLAB is started again, enter the command load and the variables will be restored to the workspace.

Section 5 Matrix Building Functions
The following are convenient matrix building functions:

eye		identity matrix zeros 		matrix of zeros ones		matrix of ones diag		create or extract diagnols 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 toeplitz

For example, zeros(m,n) creates a m x n matix of zeros, and zeros(n) produces a n x n matrix of zeros. If A has already been defined as a matrix, then zeros(size(A)) will create a matrix of zeros that is the same size as matrix A.

If x has already been defined as a vector, diag(x) creates a diagonal matrix with x down the diagonal. If A has already been defined as a square matrix, then diag(A) creates a vector consisting of the diagonal of A.

Matrices can also be built from blocks consisting of other matrices. For example, if A is defined as a 3 x 3 matrix, then B = [A, zeros(3,2); zeros(2,3), eye(2)] will be 5 x 5 matrix.

Section 6 For, While, If, and Relations
As with other computer programming languages, MATLAB has the flow control statements For, While, If, and Relations.

For
For loops are started with the command. For example, one of the most simple examples of a for-loop is:

for j=1:4, j end Here, a loop is cycled through, setting the variable j to 1, then 2, then 3, and then 4, and showing each of these outputs in the command window.

Another example, for a given "n", the statement: x=[]; for i=1:n, x=[x,i^2], end which is the same as x=[]; for i=1:n x=[x,i^2] end will produce a certain "n" vector. The statement, x=[]; for i=n:-1:1, x=[x,i^2], end produces the same vector but in the reverse order.

The statements for i=1:m for j= 1:n H(i,j) = 1/(i+j-1); end end H generate an m-by-n Hilbert matrix.

Note: Using the semicolon in the code stops MATLAB from printing unwanted intermediate results.

MATLAB allows for any matrix to be used in place of 1:n. The variable just consecutive assumes the value of each column of the matrix.

While
While loops are done in the exact same way using the command. The general form of the  loop is:

relation


 * statements



As expected, the  loop will continue to be executed as long as the relation remains true.

A basic  loop example is given below. n=0; while n<5 n=n+1; n end This loop cycles through, increasing the variable n by 1 until the relation is no longer true.

If
The  command allows for various if-then statements to be executed. The general form of the  loop is:


 * relation


 * statements



As expected, the  command executes only when the relation is true.

A basic  command example is given below. n=0; if n==0 n=2; n end Here, we set n=0, so the relation is true and theprint statement exectues accordingly. If the code was repeated, n would now be equal to 2, so nothing would be printed.

Multiple branching is also possible. This is done with  and   commands, as shown below. n=x; if n>0 m='Positive'; elseif n<0 m='Negative'; else m='0'; end

We can see how the output changes depending on the value of x.

Relations
MATLAB uses typical programming relationship operators: <    less than >    greater than <=   less than or equal to     >=    greater than or equal to     ==    equal ~=   not equal Note: The assignment statement "=" is different from the "==" relationship operator.

You can also use these logical operators in conjunction with the relationship operators: &    and |    or     ~     not

When applied to scalars, the relation is the scalar 1 if the relation is true, and 0 if the relation is false. For example, executing 1<2 prints "ans = 1", however, if you enter 2<1, the result is "ans = 0".

These relationship operators can also be applied to matrices. If the are the same size, the output is a matrix of 0's and 1's giving the value of the relation between corresponding entries.

Note: if you wish for a statement to be executed if matrices A and B are equal, you could type:

if A == B  statement end

but the seemly obvious opposite below would not execute as expected:

if A ~= B  statement end This statement would only execute if each of the corresponding entries was different. So, alternatively, to execute a statement from two matrices that were even one entry different, you would use:

if A == B else statement end

Section 7 Scalar Functions
Many MATLAB functions are used mainly on scalars. A list of the most common include: sin            asin             exp                    abs               round cos            acos             log (natural log)      sqrt              floor tan            atan             rem (remainder)        sign              ceil

Note: The operate element-wise when applied to a matrix.

Section 8 Vector Functions
Other MATLAB functions operate essentially on a vector (row or column), but act on an m-by-n matrix (m$$>=$$2) in a column-by-column fashion to produce a row vector containing the results of their application to each column.

For example: m=[1,3;2,4]; mean(m) gives the result: ans =

1.5000   3.5000 As you can see, the mean of 1 and 2 is 1.5 and the mean of 3 and 4 is 3.5.

This means that in order to find the maximum entry in a matrix A, we use max(max(A)) rather than max(A).

Note: Row-by-row action can be obtained by using the transpose; for example, mean(B')'.

Some of these vector functions are listed below: max         sum          median          any min         prod         mean            all sort                     std

Section 9 Matrix Functions
MATLAB is especially useful when using any of its various matrix functions. Some of the most useful include: eig      eigenvalues and eigenvectors chol     cholesky factorization svd      single 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

Note: Some of these functions may have single or multiple output arguments. While  produces a column vector containing the eigenvalues of A,   produces a matrix U whose columns are the eigenvectors of A and a diagonal matrix D with the eigenvalues of A on its diagonal.

For example, if m=[1,2,3;4,5,6;7,8,9], then [u,d] eig(m) outputs:

u =

-0.2320  -0.7858    0.4082        -0.5253   -0.0868   -0.8165        -0.8187    0.6123    0.4082

d =

16.1168        0         0              0   -1.1168         0              0         0   -0.0000