User:Eml4500.f08.group/Homework1/MATLAB

Link to MATLAB Primer: http://apollo.mae.ufl.edu/~vql/courses/feem/matlab_primer_3rd.pdf

MATLAB PRIMER IS OFFLINE - FOUND SECONDARY LOCATION! http://www.uib.no/med/avd/miapr/arvid/MOD3/Matlab/matlab_primer_3rd.pdf Eas4200c.f08.carbon.clausen 04:01, 12 September 2008 (UTC)

To enter source code use:

Eas4200c.f08.carbon.clausen 18:31, 12 September 2008 (UTC)

=MATLAB PRIMER NOTES=

1. Accessing MALAB.
MATLAB can be accessed in a variety of ways. For example, most systems can access MATLAB by using the “matlab” system command. Similarly, MATLAB can be shut down using the internal MATLAB command of “quit” or “exit”. Since a MS Windows operation system is being used, MATLAB is accessed through the Windows start menu and closed via the red “X” icon in the upper right corner of the open MATLAB window.

Again, since Windows is being used, it will be convenient to keep both MATLAB and a text editor open in separate windows. Reasons for this will be discussed in section 14 (Managing M-files).

2. Entering matrices.
MATLAB functions via the use of rectangular matrices. Numbers, vectors, and variables can all be represented as a matrix with numbers coming in the form of a 1x1 matrix, vectors as 1xN / Nx1, and variable as an NxN matrix (N = 1,2,3…). Matrices can be generation by built in MATLAB functions, loaded from document files or external data files, and be entered directly as a list of elements. For example, typing into MATLAB generates a 3x3 matrix of numbers assigned to variable A.

MATLAB also accommodates the use of imaginary numbers in calculations. Complex matrices can be entering in one of two ways. Entering will generate the same complex matrix. The variable i and j denote complex values in MATLAB. New complex variable may be generated by entering into MATLAB. This will assign the variable ii equal to an imaginary number thus allowing for its use as a complex variable.

Loading large arrays into MATLAB is best accomplished by utilizing as ASCII file from a text editor. This file should consist of a rectangular array of matrix values. This file can then be loaded into MATLAB with the command “load file.ext” where file is the name of the file and .ext if the file extension.

Three built in MATALB commands can be used to generate matrices. Entering rand(n) or rand (m,n) will create a (n x n) or (m x n) matrix of random numbers. The magic(n) command will create a (n xn ) matrix in which all columns, rows, and diagonals have the same sum. Finally hilb(n) will create a (n x n) Hilbert matrix.

Individual matrix numbers can be accessed by entering A(2,3)). This command will find the numerical value assigned to the second row of column three in matrix A.

3. Matrix operations, array operations.
There are several matrix operations that are available for use in MATALB and they apply to both matrix and scalar operations. Should there be incompatibilities in the size of the matrices to be operated on, an error message will result. The following are available matrix operators.

Some of the above matrix operations do not operate entry-wise. The ones that do not (*, ^, /, and \) can be made to operate entry-wise by preceding them with a period.

4. Statements, expressions, and variable; saving a session.
MATLAB is an expression based language where expressions are composed of operators, and variable names. These expression usually take the form of “variable = expression.” The resulting matrix is then displayed on the screen and assigned a variable. Should no variable be assigned by the used, a standard variable of ans (answer) is assigned to the matrix.

Statements usually terminate at the end of a single line. In the case that a longer statement is necessary, three periods (…) followed by pressing return will continue the statement onto the next line. Conversely, several statements can be placed on a single line of code provided that each expression is separated by commas or semicolons. By placing a semicolon at the end of a line, the expression is evaluated but not printed to the screen.

It is important to note that MATLAB is case sensitive i.e. the variable “A” is not the same as variable “a”. Should it be necessary, typing the command “who” will list are current variable in the workspace and any variable may be removed by typing “clear” followed by the variable name that the user wishes to clear. Infinite loops can be broken by pressing “ctrl-break” on the keyboard

All data and variable names are lost whenever MATLAB is exited unless the save command is used. Using this command will restore the workspace to its previous version the next time MATALB is opened.

For Loop
For loop syntax example, to produce a certain n-vector for a given n:

or can be written:


 * Note: x = [] creates an empty matrix

The for statement permits any matrix to be used instead of 1:n. The variable consecutively assumes the value of each column of the matrix. The following example shows this syntax as it sums all the entries of matrix A by adding its column sums.

While loop
General form:

The statements will be repeated continuously while the relation is true. Once the relation is no longer true the loop ends.

An example for a given number a, will compute and display the smallest nonnegative integer n, such that 2^n >= a:


 * Note: The semicolon after the statement keeps the values of n from printing on screen until after the loop is over and then the program calls to print n on the screen.

If statement
General form:

The statements are executed only if the relation is true.

Multiple branching is also possible as shown in the following example:

Relations
The relational operators in MATLAB are:


 * Note: = is used in an assignment statement while == is used in a relation

Relations may be connected or qualified by the following logical operators:

When applied to scalars a relation is just the scalar 1 (if true) or 0 (if false). Similarly for matrices of the same size a relation is a matrix of 1’s or 0’s. When a relation between matrices is interpreted by a while or if to be true each entry of the relation matrix must be nonzero.

Examples:
To execute statement 	when matrices A and B are equal:

To execute statement when A and B are not equal:

Or


 * Note: The above example does not work with the syntax:

This will not give the intended result because statement would only execute if each of the corresponding entries of A and B differ.

7. Scalar functions
A scalar function is one whose range is one dimensional and is made up of one or more variables. In MATLAB scalar functions generally operate on scalars, but will operate element-wise on matrices. some of the more common functions are:

8. Vector functions
A vector function is one whose range is three or n-dimensional. In MATLAB these functions generally operate on a vector. When applied to matrices in a column-by-column fashion to give you a row vector. If row-by-row action is desired it can be generated using the transpose. Some of the more common of these functions are:

10. Command line editing and recall
Editing the command line is very simple in MATLAB. Positioning of the cursor can be done with the left and right arrows. Backspace and Delete can be used to remove characters to the left and right of the cursor respectively. Edits can also be made to previous commands by using the up and down arrows to scroll through the commands to find the one you wish to edit and execute again. These edits work best for small projects and revisions.

11. Submatrices and colon notation
Colon notation is used to produce vectors and to reference submatrices. Colon Notation in addition to subscripting by key vectors are necessary to effectively manipulate matrices. They can also be used in place of loops to make the code more readable and simple. The formula for the colons is initial value: increment: terminating number. An example of this is: The Incrementing value can also be left out, causing the default of one o be used, such as: Colon Notation can be used to obtain submatrices of a matrix. An example of this is:

12 M-files: script files, function files
“M-files” are an integral part of MATLAB as they are files which can execute a sequence of statements stored in diskfiles – they are designated by the extension “.m” appended to the end of the filename. “M-files” can be broken down into two distinct forms: script files and function files.

Script files:

Script files are “M-files” which can contain a number MATLAB commands which can be executed by calling the script file by name. The advantage of a script file is evident; a single MATLAB command will actually execute a series of previously developed commands. Script files can be used to easily input data into a function, such as a matrix, which can help reduce entry errors. It is important to note that script file variables are global; and, the effect of the global variables contained in script files is that variables of the same name in the current MATLAB window will be altered by running the script command.

Function files:

Function files are another type of “M-file” similar to a script file, but allowing for (in certain ways) more control over how MATLAB handles an occurrence of this file type. Function files allow users to create their own functions in MATLAB, which can be used as any ordinary MATLAB function would (such as how “sqrt” is a MATLAB function that takes the square root of a number or of the value of a variable). A key difference between function files and script files is that variables in function files can be made either global or local – meaning that local variables can be created that pertain only to the function file (and thus a variable with the same name in a current MATLAB session would be unaffected by a call to the function file).

13 Text Strings, Error Messages and Input
Text strings are variables that contain a series, string, of characters. They are created by assigning text in single quotes to a variable name as exemplified below.

The function disp displays text strings.

However, the function error is better suited for displaying error messages as it also aborts execution of an M-file.

The user can be prompted to enter data during runtime of an M-file with the function input. This function assigns user input to it's return value. The return key denotes end of user input.

14 Managing M-Files
MATLAB has the ability to execute system commands without exiting MATLAB with the !-feature. Precede any system command with '!', for example.

This allows you to edit M-files without exiting MATLAB. For modern computers using a graphical user interface, simply opening the text editor in a new window is much simpler.

MATLAB also has a variety of debugging tools for M-files. Type help dbtype or see the last section for more details.

In MATLAB, the pwd command returns the name of the present working directory. dir or ls will list it's contents. If you only wish to see the M-files in the working directory use the what command. delete can be used to delete a file and type shows a M-file on the screen. These duplicate many common system commands while avoiding the use of the '!'.

Use the why command for entertainment

To use M-Files they must be in a directory accessible to MATLAB. M-Files in the current working directory are always accessible, as are M-file in a subdirectory of the home directory on most network installations. To see a list of directories currently in MATLAB's search path, or add and delete directories from the search path, use the path command.

15 Comparing efficiency of algorithms: Flops, tic and toc
MATLAB provides two method for measuring the efficiency of an algorithm. These are the number of floating point calculations (flops) and the elapse time it took to preform the algorithm. Note however that modern computers are time sharing machines and so elapse time may not be a reliable measure of efficiency. The computer may be busy performing another task in the middle of yours, adding to your task's time.

To measure elapse time, use the tic and toc commands. tic starts the time while toc returns the elapse time since tic was called. For example:

To measure the number of floating point calculations, use the flops and flops(0) commands. flops(0) resets the flop counter to zero and flops returns the current flop count. For example:

16 Output format
The precision of the displayed output can be controlled with the format command. This doesn't effect the computations themselves, which are always done in double precision. The format chosen from the table below remains in effect until changed.

additionally the command format compact will suppress blank lines while format loose will unsurpress blank lines. These do not effect which of the other format commands are active.

17 Hard copy
Command:  filename

This command pulls up the hardcopy and copies the content excluding graphics to that file, and will go to a default file if no filename is given. It continues to copy to the file until you command it to  or.

18 Graphics
MATLAB plots curves, 3D plots of curves , #D mesh surface plots , and 3D faceted surface plots. allows you to preview these features.

Planar plots
The command  creates an x-y plot as shown below the format for the range is 'lower rang:meshsize: upper range'.

Figures can be suppressed or exposed as the "current" figure by the command according to its figure number, and command   will give you the number of the current figure.

To make graphs, first put a function in an M-file then command it open with a domain:

Parametric graphs can also be defined as shown:

To enter text in the graph, follow these commands:

title of graph x-axis label y-axis label text on graph (placement defined by mouse) text position at specific coordinates places grid on the graph axis limits makes standard axis for all graphs auto-scaling shows current scaling for vector v puts same scale on both axes puts same scale and tic marks on both axes turns off both axis scaling and tic marks turns on both axis scaling and tic marks

Put the  commands after the   command.

To make multiple plots on a graph the format may be one of the two as follows

You can also command  to freeze the current plot and from there superimpose another plot on the same graph. This can be turned off with. To make line types use the codes: solid(-), dashed (--), dotted, dashdot (-.). To make marktypes, use the codes: point(.), plus (+), star (*), circle (o), x-mark (x). To make colors, use the codes: yellow(y), magent(m), cyan(c), red(r), green(g), blue(b), white(w), black(k). An example is a green dotted line:.

Several other features are:

Graphics hardcopy
To send the graphics to the printer, command, while   filename saves the figure to the specified format or to a default format if not specified.

3-D line plots
An example format of a 3-D line plot is as follows:

A 3-D graph has all the same commands plus.

3-D mesh and surface plots
3-D mesh plots shows a plots of matrix z with the command. A surface plot is controlled by. To obtain a mesh graph of a function over a rectangle, an example is as follows:

The shading can be  and are entered after the   command. Color profiles may be:.

Handle Graphics
To see a more complete list of the options to control a graph enter  and.

19 Sparse matrix computations
MATLAB generally assumes a matrix is dense, meaning that there is a possibility that any entry in the matrix could be non-zero. When a matrix has enough zero entries calculation time could be reduced and less memory will be needed to store the non-zero entries of the matrix. For this reason solutions to lager problems could be possible. MATLAB takes advantage of this by having two storage modes with the following functions: full and sparse.

The Following commands are used to create sparse matrices: