University of Florida/Eml4500/f08.FEABBQ/HW1/Matlab

Homework 1: Matlab Section
BACK TO FEABBQ/HW 1

Entering matrices
Matlab works completely with matrices.

Matrices are created through 3 different methods. 1. By an entered explicit list of elements 2. By generating a built-in statement or function 3. Loaded from an external file

Matlab also allows for complex numbers. You may use i or j.

If i or j are used as variables. A replacement imaginary unit may be created.

Many built in functions are available in MATLAB. The function rand may be used to created a matrix with randomly generated entries. rand (3) ans = 0.9501   0.4860    0.4565        0.2311    0.8913    0.0185        0.6068    0.7621    0.8214

rand (2,3) ans = 0.4447   0.7919    0.7382        0.6154    0.9218    0.1763

Function magic will create a martix with a magic square.

Function hilb will create a Hilbert matrix.

Individual numbers from a matrix may also be accessed by using a similar command example below.

Matrix operations, array operations
There are multiple matrix operations available. They can be used for scalars and matrices. They are

Operations can be made to operate entry wise by preceding them with a period.

[1,2,3,4].^2   ans = 1    4     9    16

[1,2,3,4].*[1,2,3,4]   ans = 1    4     9    16

Statements, expressions, variables; saving a session
MATLAB statements are usually of the form variable = expression To suppress printing of a statement you must follow the statement with a semicolon. MATLAB IS case sensitive. Therefore when creating variables keep in mind the case of the letter. The statement who will list the variables currently created and available.

To clear a variable simply write clear variable.

A runaway display can be stopped by pressing CTRL-C.

Lastly to save a session simply press the same button or go to file->save. If a session is not saved it will be lost, thus losing all variables created.

Matrix building functions
Here are few examples

B = zeros (size(A)) B = 0    0     0         0     0     0         0     0     0

diag(A) ans = 1        5         9

diag(diag(A)) ans = 1    0     0         0     5     0         0     0     9

B = [A,zeros(3,2); zeros(2,3), eye(2)] 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
These are all commands that will generally be used in M-files.

FOR will set a limit to the number of iterations that will run in a file. For instance

This code will make q = x^2 as long x is between 1 and n.

WHILE will set an end to a loop by stating the values needed to exit the loop.

This code will raise n by one as long as 2^n is less then a.

IF will not run a code unless the starting conditions mach the relation given with if.

RELATIONS Here are a list of the relational operators in MATLAB

<   less than

>   greater than

<=  less than or equal

>=  greater than or equal

==  equal

~=  not equal

Relations may be connected by

&   and
 * or

~   not

Scalar functions
built in functions that operate on scalars or individual elements of a matrix. The most commonly used of these functions are as follows:


 * sin
 * asin (arcsin)
 * exp (exponential)
 * abs
 * round
 * cos
 * acos (arccos)
 * log (natural log)
 * sqrt
 * floor
 * tan
 * atan (arctan)
 * rem (remainder from division)
 * sign
 * ceil

Vector functions
functions perform actions on vectors in a "column by column" fashion and produce a row vector. The transpose can be used to operate on a row by row basis. Some of those functions are:


 * max
 * min
 * sort
 * sum
 * prod
 * median
 * mean
 * std
 * any
 * all

Matrix functions
The following is a list of matrix functions for Matlab. These functions can be accessed using different commands.
 * 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)

Command line editing and recall
Matlab Editing and function keys:


 * left/right arrows scrolls the cursor left and right


 * up/down arrows scrolls up and down from line to line


 * backspace deletes the character left of the cursor


 * delete deletes the character left of the cursor


 * home moves the cursor to the beginning of the line


 * end moves the cursor to the end of the line


 * There is a graph for this section I just have to figure out how to add it.***
 * I guess you use the 'upload file' in the up-left corner, -andy

Submatrices and colon notation
Matlab allows for the simple creation of vectors with it's "colon notation", whose main operator is the ":", which means "everything." In the following example, a row vector is generated with a starting value of 0.2 and includes "everything" in between 0.2 and its final value, 1.2. The 0.2 in between the colons represents the step-size, meaning that the next value from the starting value is 0.2 over, and the next value after that is 0.2 over, and so on. Other examples of the use of the colon follow.

The following are more advanced uses of the colon operator.

M-files: script files, function files
Matlab has a built-in programming language, wherein commands that are usually typed at the prompt can be saved to a file (called an M-file because of its .m filename) and run all at once. There are two types of M-files: script files and function files.

A script is akin to a recipe, where commands are read top-down and executed in that order. Common commands (as well as more advanced commands) can be placed in a script so that they can be eaily executed. Inside of a script file, functions can also be called. Note that the definition of a function must exist in its own M-file, hence the second type of M-file, the function file. An example of function files follow.

Learning to write scripts and functions in M-files is essential to gaining proficiency in Matlab use.

Text strings, error messages, input
Like other programming environments/languages, Matlab has many ways of handling text. To assign a string of text to a variable, enclose the text in single quotes. This method is useful if the text is to be operated on or changed later on. To directly display text, use the  function, which is useful for simple messages. The following is a lighthearted example When programming, it is often desirable to handle errors and use text to display a readable message. The previous example shows the error message if the code was expecting a symmetric matrix and received otherwise. Another common use of text is to take in user input interactively. The previous examples takes in user input and assigns the data to the variable iter. Normal execution of the program then follows.

Managing M-files
The command  opens the M-file editor while simultaneously closing down the Matlab prompt. While this frees up RAM, it may be inconvenient to have to reopen Matlab and possibly redefine variables and other workspace entities. In order to keep Matlab open whenever running a command that would normally close Matlab, simply precede the command with an exclamation,. The following code opens the M-file editor; upon exiting the editor, Matlab is opened up in the same state as it was before closing. To sum up the introduction to M-file programming, we present common tools to use: debugging, setting directories and working with files. The following is the output of the  command.

Comparing efficiency of algorithms: flops, tic, toe
The term flops is used in computer science to designate the number of floating point operations performed (hence the name flops). In Matlab, the command  can be used to gauge how computationally intensive a section of code (or an entire M-file or script) is numerically. The usage is detailed as follows: A special note, with version 7 of Matlab, flop counts are no longer available, though another method of gauging performance of a section of code is to use the  and   commands to time the length of execution. The usage is similar to : An example of this would be
 * 1) set the number of flops to 0 with the command .  This should happen at the beginning of your code.
 * 2) At the terminating point (the point after the code whose flops are desired), simply place the command.
 * 1) At the starting point of the code to test, enter the command.
 * 2) At the point where the desired execution time is located, enter the command.

Output format
Any standard computations performed in Matlab are done in double precision. It is possible to control the appearance of the output with the following commands. The following example used is  and the format option is followed by the output,

Hard Copy
Sometimes it is desirable to obtain a hardcopy of your Matlab work, i.e. a printed version. With the exception of graphics, it is possible to save everything on screen to a file with the following command, The  function can be controlled using the commands   and , which determine when to stop and restart the recording of on-screen contents, respectively.

Graphics
Matlab is capable of producing a variety of mathematical graphs and figures in 2 and 3 dimensions. The basic commands to use these functions are:

Planar 2d Plots

The plot(x,y) function will create a linear graph if x and y are both 1d vectors of the same length. The first variable in the plot function is the horizontal axis, and the second is graphed on the vertical. The easiest way of producing a 1d vector is using colon notation:



The following is a graph of a sin wave from -4 to 4. Adding shown in the code above is the syntax for adding titles and axis labels using the title and xlabel/ylabel commands respectively.

Streamlined code exists for graphing functions as well. First, an M-file must be created such as the following:



Using this code would now create a 2d graph from -1.5 to 1.5:



2d parametric graphs can also be created in Matlab. The following code and Figure 3 demonstrate:

Annotating Graphs

Graphs are easily annotated in Matlab as well. Typing in the following commands will label the active figure. The format is like:

Other visual features are available as well:

All of these visual modifications should be performed after the plot command.

Multiple Graphs on the Same Figure

There are different ways to place multiple graphs onto the same Matlab figure. The first is to overload the  function. The following code and Figure 4 show how this can be done:

The  command can also be used. When hold is on, every plot graphed will go onto the active figure. Turning hold off will create a new figure for each new graph, which is the Matlab default.

Using Different Colors and Line Types on Graphs

Sometimes the default blue solid line in Matlab graphs can get a little boring. To add a little variety to your graphs, there are several commands that can be incorporated into the  function:



These commands are used inside single quotation marks inside the  function. would plot a dashed red line and  would plot a green dotted line.

Other Types of Graphs

There are several other types of graphs which Matlab can produce. Although this guide does not have the details for them, they can all be easily found using the  command.


 * Polar
 * Bar
 * Hist
 * Quiver
 * Compass
 * Feather
 * Rose
 * Stairs
 * Fill
 * Subplot

Graphics Hardcopy

Oftentimes it is necessary to print a graph from Matlab. This is most easily done with the convenient 'Print' menu option on the Figure. It is normally easier though to use 'Save as' and save the graph as a .jpg or other type of graphics file. For the more adventurous, Matlab has a  command which will print the active graphics item. The  option can also be used to append a different saved file to the current graphics item for printing. Just use the format.

3-D Line Plots

There are few more impressive ways to show off Matlab skills than producing colorful 3-D plots. The  command can easily plot in 3 dimensions, just like   plots in 2 dimensions. The following example shows how a 3-D plot (Figure 6) can be parametrically created:



All of the settings applicable to 2-D plots (including axis labels and commands, titles, colors, etc) can be used on a 3-D plot as well.

3-D Mesh and Surface Plots

The mesh and surf functions can create 3 dimensional representations of matrices, either with a wire mesh or solid surface. If a single matrix can be inputed into either function, the z value is the matrix value at point (x,y) (row, col). Figures 7 and 8 show the mesh and surf functions being used to graph the 'eye' (identity) matrix:



3-D functions can also be graphed using mesh and surf in conjunction with the  function. Combined with colon notation,  creates an x-y rectangle in which a function is graphed. The following code and Figure 9 show how a 3-D function can be defined and graphed:



There are several ways to change the appearance of a 3-D graph in Matlab. First of all, the  command will affect the superimposed mesh lines on a surface graph. Various color profiles can also be experimented with. The following commands can be used like this:

Any of the functions to change the appearance should be used after the graph has been made.

Graphs can also be produced parametrically with M-files. Check the guide for further information on this, and Matlab's 'Handle Graphics' which can produce advanced graphs and plots.

Sparse Matrix Computations
Matlab typically handles matrices of which the contents are mostly nonzero. These matrices are considered "dense". A matrix with mostly zero entries is considered "sparse" and is worth defining for the possibility of ignoring the zero values and operating on the nonzero values only. The benefit of this is to reduce the memory footprint of the matrix and the computation time. Suppose a matrix is created by the following command, and that the matrix is filled with mostly zeros by the following command, the output of which looks like The nonzero values of the matrix can be easily found with the command, followed by the output, The following commands will return the matrix to it's previous form and check it's storage mode, respectively Sparse matrices can also be generated directly as opposed to calling the sparse function on a full ("dense") matrix. A sparse diagonal matrix can be generated with the  command. The output is similar to calling the. are the sparse analogs of, respectively. A more specific approach would be to define the nonzero values of the sparse matrix individually. For example (followed by output) The nonzero entities were stored in the row vector. Another example of directly defining the nonzero values of a sparse matrix is The output of Matlab arithmetic and functions will be in one of the two storage modes (either Full(F) or Sparse(S)). The following defines the output results of the manipulation done to either full or sparse matrices