User:EML4500.f08.RAMROD.E/HW1

= Matlab Summary =

Intro
Matlab is a software program, developed by Matrix Laboratories, that uses matrix-based mathematics to solve ordinarily difficult scientific and engineering applications. It has several advantages over traditional methods (i.e. Fortran or C++), specifically its ease of use, versatility of capabilities, and its ability to convey results graphically as charts and its ability to model very complex systems visually for ease in conveyance of results. Since its development, Matlab has become very widely used in nearly all scientific fields and, especially in engineering practice, has become an absolutely vital tool for all types of engineering analysis.

Matrices in Matlab
As was stated above, Matlab is a matrix-based program. Thus, all variables, whether scalars, vectors, or much more complex and larger-scale matrices are all stored in the same manner. Because of the significance of matrices in this program, the first, and most important operations to know are those involving matrices.

Creating Matrices
There are several ways in Matlab to make new matrices. One method is to enter the values directly. For example:


 * A = [2,3,4;5,3,6;9,5,2]


 * A = [2 3 4; 5 3 6; 9 5 2]

Both of these entry syntaxes would create a 3x3 rectangular matrix with the indicated values. Other permissible formats are for scientific notation, such as [2.34e-4, 3.53e8], or for complex numbers, entered as [2+4i,3+8i] or [2,3] + i*[4,8]. In both instances (exponential and complex numbers) spaces should be avoided between numbers and commas should be used. When manually entering values into a matrix, as shown in the above examples, commas (or spaces where allowed) separate entries in a row while a colon separates one row from the next.

Another option for creating matrices is to read from an input file, usually an ASCII file from another editor on your computer. This is completed by using the load command. To load input file "input.dat", the command would be load input.dat.

After creating a matrix, it can then be referenced by its name (i.e. A). Also, you can reference individual entries such as A(4,2) for the second entry in row four of matrix A.

Matrix Building Functions
In addition to creating your own matrices, Matlab has several default "special" matrices and matrix references that can be called on using their reserved names. The following are a few of the standard Matlab matrices and uses:


 * eye(m,n) will create the identity matrix of dimensions mxn.
 * zeros(m,n) will create a mxn matrix where all entries are zeros.
 * ones(m,n) will create an mxn matrix where all entries are ones.
 * diag(x) will create a matrix where the diagonal is the predefined vector x.
 * triu(x) or tril(x) references the upper or lower triangle of matrix x, respectively.
 * rand(m,n) will create an mxn matrix with Matlab randomly generating values for each entry that will be uniformly distributed between 1 and 0.
 * magic(m,n) will provide an mxn matrix that is a "magic" matrix in which each column, row, and diagonal totals to the same sum.
 * hilb(m,n) creates an nxn Hilbert Matrix.

It is useful to note also that creating a square matrix of any of the above forms is done by replacing the (m,n)dimensions by simply an (n) dimension.

Also, any of these matrices can be created to match the size of an existing matrix by using the command size(X) where X is a matrix. For example, eye(size(X)) creates an identity matrix with the same dimensions as matrix X.

All of these commands are extremely useful as starting points for building matrices. For example, A = eye(2) could then be edited (A(2,1)=5) to modify it from an identity matrix to the desired matrix without manually entering the value of each entry.

Matrix Operations
Once a matrix is created using the above stated methods, Matlab has several built in operations to manipulate it mathmatically. The following are the basic matrix operations that Matlab can perform:


 * +: addition - adds two matrices term by term to create a new matrix.
 * -: subtraction - subtracts two matrices term by term to create a new matrix.
 * *: multiplication - multiplies two matrices together
 * ^: power - raises a matrix to power indicated after ^.
 * ': conjugate transpose - returns a matrix where each term's indices are swapped (Aij goes to Aji) and all terms are replaced by their complex conjugate (a+bi goes to a-bi).
 * \: left division - A\b = b/A.
 * /: right division - normal division of two matrices.

While addition and subtraction above execute a term by term operation, the others do not. However, Matlab will allow this by placing a period before the operator. For example:

"[2,5,9,7].*[2,5,3,1] = [4,25,18,7]"

This form of multiplication, division, or exponents can be found very helpful when working with Matlab Graphics which will be described later.

Statements, expressions, and variables in Matlab
In addition to being a matrix-based software, the language of Matlab is expressions. Expressions are used for every function that Matlab is capable of. Generally, an expression can take the form of a equation or a simple statement.

Equations
Equations, such as Y = 5X+5, are generally created by stringing together variables, functions, and operators and results in a matrix that is then output to the screen and can be referenced in later functions.

Statements
If a certain variable and equals sign is not specified, 5X+5, this expression results in a newly created variable "ans" whose value is stored until a new expression is evaluated. For this case, the line ans = (value) will be output to the screen. However, if the expression is followed by a semicolon, 5X+5;, this line will not be shown. This is very convenient in long iterations where extra lines of output answers only complicate the code and calculations and are undesired.

Variables
An important thing to note here is that Matlab is case-sensitive, meaning that the variable y is not the same as the variable Y. If at any given time you wish to see a list of the current variables, the command "who" or also whos will print the list and their values to the screen. Additionally, variables can be cleared by the command clear followed by the variable name you wish to clear. The command clear by itself will clear all non-permanent variables in the cache.

Saving a Session
In order to not lose variables when you exit Matlab, it is very useful to know the save command. This will write all variables and their values to a non-accessable file named "matlab.mat". Upon entereing Matlab the next time, simply typing the load command will access the file and will bring back all variables as they were when the file was saved.

Scalar, Vector, and Matrix Functions
Matlab has many predefined functions that are very useful in doing matrix calcluations. Some are solely used for scalars matrices (1x1), some for vectors, and the most powerful are the matrix functions.

Scalar Functions
The below functions are designed to work with scalars only, but can be applied to a matrix. When the following are used in reference to a matrix, the operation is computed term by term in the matrix.

"*sin - returns sin of each entry" "*cos - returns sin of each entry" "*tan - returns sin of each entry" "*asin - returns arcsin of each entry" "*acos - returns arccos of each entry" "*atan - returns arctan of each entry" "*''exp' - returns e to the value of each entry" "*log - returns natural log of each entry" "*rem - returns remainder of each entry" "*abs - returns absolute value of each entry" "*sqrt - returns square root of each entry" "*sign - returns sign of each entry" "*round - rounds each entry to the nearest whole number" "*floor - returns lowest entry value" "*ceiling - returns highest entry value"

Vector Functions
As with scalar functions, the below commands are designed for vector matrices. The command is evaluated column by column and the output is a row matrix corresponding to the result from each evaluation. The vector functions are:

"*max(x) - returns maximum value in vector x" "*min(x) - returns minimum value in vector x" "*sort(x) - returns vector x in rearranged in numeric order" "*sum(x) - returns sum of all values in vector x" "*prod(x) - returns product of all values in vector x" "*median(x) - returns median of values in vector x" "*mean(x) - returns mean of values in vector x" "*std(x) - returns standard deviation of values in vector x" "*any(x) - applies a comparison to any value in vector x" "*all(x) - applies a comparison to all values x"

To apply these for an entire matrix rather than a single column, use them twice. For example, median(median(A)) would return the median of the row matrix which was returned by median(A).

Matrix Functions
Matrix functions are by far the most useful and powerful of Matlab's abilities. The following are the matrix functions and their description.

"*eig - eigenvalues and eigenvectors" "*chol - cholesky factorization" "*svd - singular value decomposistion" "*inv - inverse" "*lu - LU factorization" "*qu - 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 teh 2-norm" "*rank - rank"

Logic Functions in Matlab
As in many program languages, logic functions such as for, if-and, and while loops are essential assets to understand. In most cases these are implemented very similarly to other languages. The details of each implementation is below.

For Loops
For loops are created using a for condition, an expression, and the end commmand. For example, if you wanted to make a vector y of size n (a predifined scalar) in which each element is the previous element plus one, the code would look like that below.

"y = [];" "for a = 1:n" "y[y,y(n-1)+1]" "end"

The loop will continue as long as the condition (a=1:n) is true. This condition is saying that a is incremented by one each iteration and will continue until a=n. Each time the loop is evaluated, the expression is evaluated and the value of the variable (in this case matrix y) is updated accordingly. If you wish to print the end value of the variable in question, just type the variable name after the end command.

While Loops
While loops also operate much like in other languages. They are generally stated using a while relation, a group of statements and operations, and the end command to finish the loop. These loops differ from For loops in the fact that they will execute until the relation is false, and not simply a preset number of iterations. A simple while loop, creating a matrix of the numbers one through ten, is shown below.

"x=[];" "a=0;" "while a<=10" "x=[x,n]" "end" "x"

This code would then print out the vector x = [0,1,2,3,4,5,6,7,8,9,10].

If Loops
If loops are implemented very similarly to while loops, involving a true/false relationship, a series of statements, and the end command. However, If loops allow the user to create several different branches of elseif and else loops to allow for more than two sets of operations. For example, if there is a vector with 5 entries, you could add 3 to entries 1 and 5 while subtracting 1 from entries 2 and 3 and force entry 4 to be zero using the code below.

"X=[1,1,1,1,1]" "n=1" "5''" "X(n)=X(n)+3"

"3''" "X(n)=X(n)-1"

"else" "X(n)=zero"

"end" "X"

This would then print out the new vector X = [2,0,0,0,2].

Relationship Operators
The following are the preset relationship operators that Matlab uses in the above described loops.


 * < - Less than
 * > - Greater than
 * <= - Less than or equal to
 * >= - Greater than or equal to
 * == - Equal to
 * ~= - Not equal to

Also, the three logical operators below are used to string relationships together.


 * & - and
 * | - or
 * ~ - not

It is important to so note that when an operator is used to compare two scalars, such as 4>5, the resultant answer will be a 1 or a 0, corresponding to either true or false, respectively.

However, comparing two matrices is a bit different. The comparison if A==B is true if every term in A is the same as every term in B. The any command can get around this aspect to compare matrices more generally. For instance, the command if any(any(A==B)) will be true if any element of A is the same as the corresponding term in B and is not a global matrix comparison.

Colon Notation
One very key shortcut in Matlab is what is known as colon notation. To this point, if you desired to create a vector of all even numbers between 2 and 20, you would have had to manually enter each entry. However, in actuality, the command 2:2:20performs the exact same operation. Note that the first number is the starting point, the second the increment, and the third is the ending point. If the middle number is left out, Matlab assumes is to be one.

The colon notation can also be reference certain submatrices within already created matrices. For example, X(1:2,5) references the first two rows of column five of matrix X. If you would like to reference an entire row or column in a matrix, there is a shortcut here as well. Suppose a 200x200 matrix, A, and assume you want to perform an operation to the entire 45th column of this matrix. Rather than referencing (1:200,45), you could simply use the syntax (:,45). Matlab interprets a colon by itself to mean an entire row or column. You can perform operations to specific submatrices to create the submatrix you would like to reference and you can reference more than one row or column in a specific operations. For examples, A([5,7],:) references all columns in both row 5 and row 7 of A. Likewise, the statemnt A([5,7],:) = A([5,7],:)*[1 2; 3 4] would multiply just rows 5 and 7 by the 2x2 matrix shown.

Again, this notation and utility is something unique to Matlab and is another aspect that gives it an enormous advantage over previously used softwares and languages.

Working with Files in Matlab
In Matlab, you are able to create files, much like source files in other languages, that perform a series of operations each time they are accessed. Such files are called M-files due to their file extension, .m. There are two types of M-files in Matlab and each is discussed below.

Script Files
Script files can be thought of in Matlab as sub-programs that can later be accessed for use. A script file is just series of statements that are executed until the file is complete. In order to reference a script file, say solveatriangle.m, simply type the command solveatriangle in your Matlab code and the file will be executed. One very important thing to note and to be cautious of is that variables in script files are global and any changes made to variables during execution will be applied to all variables with the same name in your matlab code. Additionally, it is possible for M-files in Matlab to reference many other M-files, and even itself, if necessary to complete the desired operation.

Function Files
Function Files are very similar to script files, with two major differences. The first, and most important, is that all variables in a function file are local unless specified to be global.

Secondly, script files are just a sequence of operations to be performed at a specified point in the code. However, function files are input/output operations, to which one or more input variables are passed and one or more outputs are retrieved. Because of this, the first line of every function file is the function name, the input arguments, and the output arguments. The following code would be an example of a simple function that takes 5x5 matrix A as an input, adds 3 to every entry in row 5 and outputs the resulting matrix and assigns it to a new 5x5 matrix B.

"Function File"

"function B = add3(A)" "B=A" "B=B(5,;)+3"

"Matlab Code"

"B = add3(A)"

At this point, Matlab would print the new matrix B.

Obviously, function files can be far more complex and, thus, much more utile than this example. However, the basic outline and format would remain the same whether it was four lines or 400.

Text Strings in Matlab
Text strings are very important tools, usually used in M-files. They serve to prompt for input and also to alert if an error has occurred. Strings can be referenced instance by instance or can be assigned to a variable and are specified by text between single quotes ('string'). If you wish to display a message, the disp(string) command will print the string identified in the. Also, the error will behave similarly. However, error will abort execution of the M-file it is a part of. The other function of strings is to prompt the user for input. To do this in an M-file, you need to use an equation, assigning the user's input to a variable as well as the input command. For example:

a = input('Please enter the length of side a: ')

This would prompt the user to "Please enter the length of side a: ". Upon entering a value and pressing enter, the input would then be assigned to variable a and the next statement in the M-file would be executed.