University of Florida/Eml4500/f08/Matlab Summary

3. Matrix Operations, Array operationsEdit

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.


4. Statements, expressions, variablesEdit

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.


5. Matrix building functionsEdit

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

6. For, while, if and relationsEdit

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