User:Eml4500.f08.bike.mcdonald/homework report 1

 Restored after the submission deadline due to the use of a wrong namespace. Eml4500.f08.bike.mcdonald 21:27, 7 November 2008 (UTC)

Class Notes
This section will be used to summarize the class notes from August 25th - September 5, 2008 in EML 4500.

August 25th - 29th, 2008
Lectures are held at the University of Florida on Monday, Wednesday, and Friday from 4:05-4:55 PM in Florida Gym 270.

EML 4500 teaches the fundamentals of the finite element method used in the analysis of truss, beam, and solid structures. This semester, the course is being taught by Professor Loc Vu Quoc from the University of Florida Mechanical and Aerospace Engineering Department. The finite element method is taught through matrix algebra with the derivation of the stiffness matrix. Local and global coordinate systems are emphasized, as well as 3-D truss and beam structures and their linear stability. Coding and plotting is another area of interest in this course, as MATLAB programming will be used in order to solve many of the problems. Applications of the finite element method are discussed, as well as its uses in mechanical, aerospace, and biomedical engineering fields.

The text book that will be used throughout the semester is Finite Element Analysis with Mathematica and MATLAB Computations, written by M. Asghar Bhatti.

Students will be required to work in groups of 5 to 6 under a team name that is 4 to 6 characters long. Cooperative learning techniques will be used, and group member evaluations will be held at the end of the semester. These evaluations will directly impact the homework grade of that individual, approximately 31% of the overall grade. The rest of the student’s individual grade is comprised of 3 exams, each accounting for 23%.

Each group will be required to use Wikiversity in order to submit homework and projects. Each member must create his/her own personal class account where his/her portion of the work will be posted. Each members name and UFID number, as well as his/her Wikiversity class username, is to be submitted to the instructor on hard copy.

Homework and project load will be divided evenly among the team members at their discretion. Once each group member has completed his/her assigned task the assignment will be posted as a whole on the group leader’s user namespace. This should be done close to the homework deadline in order to keep other groups from stealing ideas or plagiarizing. Another safety concern is that users may change information on a students Wikiversity page. In order to prevent this type of fraud from occurring the student must save an archived version of the assignment and email that address, not the address of the updated page, to the TA.

Element Labeling
The class begins with an introduction to the nomenclature of element labeling. The figure is first drawn with all members, forces, and constraints in a global view. Each constraint is then labeled globally by an encircled number. The structure is typically numbered from left to right. Each element of the member is then labeled with a number enclosed in a triangle. The constraints are then removed and replaced with force arrows labeled as Rnx or Rny in the x and y axes respectively. The subscript n denotes the constraint node number of the global member.

Once all of the members, nodes, and reaction forces of the global member are fully labeled, a free body diagram for each member of the structure must then be drawn. The member labeled with its global member number within a triangle. The nodes are then labeled with a local node number inscribed within a square. The local reaction forces are then drawn in the x and y axes at each node. These internal forces are then labeled as fi(e) where the subscript i represents the degree of freedom (dof) of that node and the superscript e represents the element number. The displacement of each node is drawn just like the degree of freedom and labeled as di(e) with i representing the degree of freedom of that node and e represents the element number. The labeling nomenclature is illustrated below in a global (left) and local (right) view of a truss system.



Force-Displacement Relation
A simple 1-D spring element fixed at one end is used to illustrate the force-displacement (FD) relation. This relation is $$f=kd$$, where $$f$$ is the force applied to the spring, $$k$$ is the spring constant, and $$d$$ is the displacement of the spring from its natural position. The spring element can be seen below.



The relation also holds true for a spring with two free ends as seen below.



The FD relation determined by observing the spring in two ways. The first case is where the observer is sitting on node one, which appears to be stationary. The resulting equation is $$f_2=k(d_2-d_1$$). The second case with the observer on node 2 yields the equation $$f_1=k(d_1-d_2$$). The matrix of $$f=kd$$ for the above spring is presented below.



Steps to Solve Simple Truss Systems
1.     Global Picture


 * Structure level


 * Global dofs


 * o      Known part (fixed dof, constraints)


 * o      Unknown part (solved using finite element method)


 * Global forces


 * o      Known part (applied forces)


 * o      Unknown part (reactions)

2.     Element Picture


 * Element dof


 * Element forces

3.     Global FD relations


 * Element stiffness matrices in global coordinates


 * Element force matrices in global coordinates


 * Assembly of element stiffness and force matrices into global FD relation

4.     Elimination of known dofs to reduce the global FD relations


 * Stiffness matrix non-singular→inveritble


 * To be invertible unknown displacement dofs must be less than known dofs

5.     Compute element forces from known element stresses

6.     Compute reactions (unknown forces)

MATLAB Tutorial
This MATLAB tutorial is intended to introduce the basics of MATLAB to novice users. The information given has been adapted from MATLAB Primer, Third Edition, written by the late Professor Kermit Sigmon from the University of Florida Department of Mathematics.

Accessing MATLAB
Depending on the operating system and setup, MATLAB can be started by accessing an icon in a GUI or by typing  into the command line. To close MATLAB, the MATLAB commands  or   can be used.

Entering Matrices
MATLAB works only with matrices. There are a couple special case matrices though. A 1-by-1 matrix is read as a scalar, and any matrix with only one column or one row is read as a vector.

Matrices are entered into MATLAB in several possible ways. The first method is that a user will create a specific matrix. MATLAB has built in commands that will also create matrices. The final way to enter in a matrix is by using external files, using either another application, a data file, or another editor.

Matrices can be entered into MATLAB by the user in two ways: in one row using semicolons and spaces or several rows using line breaks and spaces. Both examples are shown below.

EDU>> A = [1 2 3; 4 5 6; 7 8 9]

A =

1    2     3     4     5     6     7     8     9

EDU>> B = [1 2 3 4 5 6 7 8 9]

B =

1    2     3     4     5     6     7     8     9

Matrix A was created using semicolons and spaces on one line. It is much easier and the most common way to create matrices. Matrix B was created using line breaks and spaces.

MATLAB also allows for the input of exponential and imaginary numbers. Exponential numbers can be entered using  as the power modifier. Matrix C shown below is an example of this. Imaginary numbers are entered in using  or   to indicate the imaginary part of a number. Imaginary numbers can be entered into MATLAB in two ways: creating a real matrix and an imaginary matrix as shown in matrix D or entering each number into the matrix with its real and imaginary parts as shown in matrix E. The examples are shown below. EDU>> C = [1.12e2 -2.23e-3; 4.39e-2 -9.45e3]

C =

1.0e+003 *

0.1120  -0.0000    0.0000   -9.4500

EDU>> D = [1 2; 3 4] + i*[6 7; 8 9]

D =

1.0000 + 6.0000i  2.0000 + 7.0000i 3.0000 + 8.0000i  4.0000 + 9.0000i

EDU>> E = [1+6i 2+7i; 3+8i 4+9i]

E =

1.0000 + 6.0000i  2.0000 + 7.0000i 3.0000 + 8.0000i  4.0000 + 9.0000i Matrices D and E are equal, showing that both methods are effective when entering in imaginary numbers. If variables  and   are overwritten, either imaginary modifier can be reentered using the command   or.

Matrices created in an outside editor or application can be loaded with the  command. If data is in a file named matrix.ext, where .ext is the extension, the data will be loaded into MATLAB using the command. MATLAB will read the file and then create a variable named.

MATLAB has three built-in commands that will create special matrices. The three commands are,  , and.

The  command creates a matrix with numbers randomly generated between 0 and 1. It can be used with a positive integer  to create a square matrix with the command   shown below in Matrix F or with two positive integers   and   to create a   matrix using the command   shown below in Matrix G.

EDU>> F = rand(2)

F =

0.9355   0.4103    0.9169    0.8936

EDU>> G = rand(3,4)

G =

0.0579   0.0099    0.1987    0.1988    0.3529    0.1389    0.6038    0.0153    0.8132    0.2028    0.2722    0.7468

The magic matrix is a special matrix in which each of the rows, columns, and diagonals have the sum. This matrix is required to be a square matrix. This matrix can be generated in MATLAB with the command. An example is shown below in matrix H.

EDU>> H = magic(4)

H =

16    2     3    13     5    11    10     8     9     7     6    12     4    14    15     1

The final special matrix command creates a Hilbert matrix. The Hilbert matrix is a positive and symmetrical matrix and its elements are unit fractions. It can be generated with the command. An example is shown below in matrix I.

EDU>> I = hilb(4)

I =

1.0000   0.5000    0.3333    0.2500    0.5000    0.3333    0.2500    0.2000    0.3333    0.2500    0.2000    0.1667    0.2500    0.2000    0.1667    0.1429

Matrix operations, array operations
The table below shows all the matrix operations available in MATLAB.

These operators can be applied to either scalars or matrices. If the sizes of the matrices are not correct for a certain operation, MATLAB will output the error "" where command is the corresponding operation.

The operations of division, multiplication, and power are not entry-wise operators. These matrix operators are applied to the whole matrix instead of a single entry, unlike addition and subtraction. To use one of the matrix operators in an entry-wise situation a. must be placed in front of the operator. This is shown in the power example shown below.

EDU>> [1 2 3 4].^2

ans =

1    4     9    16

Statements, expressions, variables; saving a session
MATLAB is written in a code that works with expressions. An equal sign,, is not required to carry out a command, but will assign a variable to the data. If the equal sign  is omitted, MATLAB creates a variable named   to save the data. This variable will be overwritten every time a variable is not defined in a command statement.

If a semicolon is placed at the end of a command statement, MATLAB will not display the entered data and just save it to a variable. This is useful when entering large amounts of data that do not need to be displayed after each command.

Variables are case sensitive in MATLAB. The variables  and   are not completely different variables. Since a large amount of variables can be created in MATLAB, the command  or   can be used to see all active variables. If the user wants to remove a variable, the  command can be used. To eliminate the variable  the user would use the command statement.

When a user exits MATLAB all the variables are cleared from memory. If a user wants to save the variables for future use, the command  can be used. This command forces MATLAB to write all the variables to a file named  which can be accessed later. To load the variables back, the command  restores the variables.

If a command statement is in an unending loop or is taking too long to process, the break command can be used to stop all MATLAB activity without exiting MATLAB. This can be done using.

Matrix building functions
The following table lists some built-in commands that can be used to build matrices in MATLAB.

These commands can be combined to build a matrix. Some of the commands can extract data from other matrices, such as the command. This will build a matrix of zeros the size of matrix A. An example of several commands being utilized to build a matrix can be seen below in matrix J.

EDU>> A = magic(3); EDU>> J = [A, zeros(3,2); zeros(2,3), eye(2)]

J =

8    1     6     0     0     3     5     7     0     0     4     9     2     0     0     0     0     0     1     0     0     0     0     0     1

For, while, if — and relations
The basic MATLAB flow control statements,   and   are very similar in operating nature to those in most computer languages.

For
When using  it is possible to produce vectors and matrices of useful information. In the example below, a  is used to produce an  -vector for a given.

x = []; for i = 1:n, x=[x,i^2], end

The example below will also produce an -vector with a given.

x = []; for i = 1:n x= [x,i^2] end

In the next example, the  produces the same  -vector, but in reverse order.

x = []; for i = n:-1:1, x=[x,i^2], end

In a more intricate example, below is a  that produces a  -by-  Hilbert matrix. A -by-  Hilbert matrix is a matrix whose elements are made up the unit fractions

$$ H_{mn} = \frac{1}{m+n-1} $$

The example is shown below. for i = 1:m for j = 1:n H(i,j) = 1/(i+j-1); end end H

This example not only produces the -by-  Hilbert matrix, it prints it to the screen as well. The reason it prints it to the screen is because of the last H. This H at the end of the two  loops will allow the printing of the final result. The statement located in the loops has a semicolon in order for it to not print to the screen. Therefore, instead of every intermediate step being printed to the screen, only the final result is printed.

If it is desired to use any matrix instead of, the next example is used. This example is shown below. s = 0; for c = A     s = s + sum(c); end

This example adds the column sums of  in order to sum all the entries of.

While
The general form of the  loop has two important elements, the relation and the statements. The general form is shown below. while relation statements end

In this general form, the statements will be executed until the relation is no longer true. An example is shown below. n = 0; while 2^n < a     n = n + 1; end n

In this example, given a number a, the  loop will continue to execute the statement   until the relation   is no longer satisfied. This will display the smallest integer n that will satisfy.

If
The general form of an  statement is made up of the same two components as the   loop, the relation and the statements. The general form is shown below. if relation statements end

For the  statement, the statements will be executed only if the relation is true. Multiple branching is possible with the use of different types of  statements such as the   and the   statement. An example with this branching is shown below. if n < 0 parity = 0; elseif rem(n,2) == 0 parity = 2; else parity = 1; end

In this example, if the relation  is satisfied, then it executes the statement. If the relation  is satisfied, then the statement that is executed is. If none of those relations are satisfied, the statement  is executed.

Relations
The relational operators in MATLAB are very important to know. These relational operators are shown below.

It is important to note the difference between an assignment statement and the  relation. In an assignment statement a  is used, while in a relation the   is used. Also, multiple relations can be utilized and either connected or quantified by the logical operators shown below.

Relations can be applied to scalars as well, but in this case the relations themselves are the scalars 1 or 0, depending on whether they are true or false. In the example below, it shows the simple relations between scalars and the corresponding answer.

>> 3 < 5  ans = 1

>> 3 > 5  ans = 0

>> 3 == 5  ans = 0

When applying relations to same size matrices, each element is compared to the other in the same location within the matrix, and a 1 or 0 will appear in that location, depending on whether it is true or false. An example of this is shown below. >> a=rand(5) a = 0.8147   0.0975    0.1576    0.1419    0.6557       0.9058    0.2785    0.9706    0.4218    0.0357       0.1270    0.5469    0.9572    0.9157    0.8491       0.9134    0.9575    0.4854    0.7922    0.9340       0.6324    0.9649    0.8003    0.9595    0.6787

>> b=triu(a) b = 0.8147   0.0975    0.1576    0.1419    0.6557            0    0.2785    0.9706    0.4218    0.0357            0         0    0.9572    0.9157    0.8491            0         0         0    0.7922    0.9340            0         0         0         0    0.6787

>> a==b ans = 1    1     1     1     1        0     1     1     1     1        0     0     1     1     1        0     0     0     1     1        0     0     0     0     1

When using  and , the relation between matrices is interpreted to be true only if the relation between each and every element is true. If it is desired to execute a statement only if matrices A and B are equal, then the it is typed as shown below. if A == B     statement end

On the other hand if it is desired to execute the statement when matrices A and B are not equal, then it is typed as shown below. if any(any(A ~= B)     statement   end

or if A == B else statement end

It is important to note that typing it as shown below if A ~= B     statement end

will not give the desired results because this is saying that every corresponding element of A and B differ from each other. The desired result is if A and B are different, which means that even if only one corresponding element of A and B are different. In the above example, the functions  and in other cases   can be used to reduce matrix relations to certain scalars or vectors.

Scalar functions
When using scalars, there are come MATLAB functions that operate essentially on them. When applied to matrices, however, they operate element-wise. The most commonly used functions are sin              asin               exp               abs               round cos              acos               log (natural log) sqrt              floor tan              atan               rem (remainder)   sign              ceil

Vector functions
When using vectors, there are come MATLAB functions that operate essentially on them. These functions work only on -by-  matrices by acting on each column and thus producing a row vector with the results of each column. By using the transpose of the matrix, the functions would be working row by row. Some of the functions are: Max              sum               median               any min              prod              mean                 all sort             std

An example of how one of these functions work is shown below. With the matrix A, when using the  function, a row vector showing the maximums of every column is shown. The way to get the maximum of matrix, you would have to type. >>A = 1    2     3     4        1     2     3     5        6     1     2     3        7     1     3     4

>> max(A) ans = 7    2     3     5

>> max(max(A)) ans = 7

Matrix functions
MATLAB's most important functions are matrix functions, these are the ones that give MATLAB most of its power. The most practicable are:

MATLAB functions in general may have single or multiple output arguments. In the example below, there are two different output arguments for one function,. A = 1    2     3        3     6     2        2     8     5

EDU>> Y=eig(A) Y = 11.0530               0.4735 + 1.5196i 0.4735 - 1.5196i

EDU>> [U,d]=eig(A) U = 0.3376            0.7002             0.7002                0.5128            -0.3368 - 0.2912i  -0.3368 + 0.2912i 0.7893            0.1016 + 0.5488i   0.1016 - 0.5488i d = 11.0530                 0                  0                     0             0.4735 + 1.5196i        0 0                 0             0.4735 - 1.5196i

Command line editing and recall
The MATLAB command line can be edited in several ways. The cursor is moved with the left and right arrows on the keyboard, and the backspace key deletes the character to the left of the cursor. Characters can also be deleted using the Home, End or Delete keys. The up and down arrows, on the keyboard, are used to scroll through previous commands.

A command line can be changed and rerun by scrolling up to, editing, and then executing the previous command. The plots of y=sin(mx) and y=sin(nx) from the range of 0 to 2π can be compared easily by editing the (mx) to (nx) in the following command line:

""

Submatrices and colon notation
Colon notation is used in MATLAB to generate vectors and reference submatrices. Colon notation also reduces the use of loops and simplifies codes.

The expression 1:4 is a row vector [1 2 3 4]. Neither the vector numbers nor the increment have to be integers. The example,

yields the vector

To count down, a negative sign is used in the vector notation.

yields

Colon notation is also used to recall submatrices within a matrix. An example

is a column vector made up of the first three values in the second column of the matrix.

A lone colon calls an entire row or column:

is the entire second column of the  matrix. Vectors can be used within colon notation to recall multiple columns.

recalls the entire columns two and five of the matrix.

Columns can be replaced in one matrix from another using colon notation for Example,

replaces columns two, three, and five in matrix  with columns two, three, and four from matrix.

M-files: script files, function files
MATLAB can run a sequence of statements that are stored in disk files, called “M-files.” M-files end with “.m” in the filename and are usually created with a local editor. The two types of M-files are script and function files.

Script files
Script files contain normal sequences of MATLAB statements. The file  will be run in MATLAB by imputing the command. Variables in the M-file are global and will replace the values of same named variables in the MATLAB environment.

Script files also allow for large matrices to be entered and corrected easily. A matrix can be input, for example, by entering diskfile data.m

A = [ 1 2 3 4 5 6 ];

Running the MATLAB command data will cause the matrix A to be created and stored in the MATLAB environment. An M-file can call on other M-files, or it can run itself repeatedly.

Function files
Function files allow for the creation of new functions that do not exist in MATLAB already, needed for a specific problem. Function variables are set as local variables by default.

An example of a function file:

function a = (sin(m))^(-1) %INVSIN computes inverse sin. % invsin(m) returns inverse sin
 * A = 10*invsin(m);

This example should be in a diskfile named  due to the function name. The first line declares the function name, input arguments, and output arguments. Without the first line the function file would be a script file. A MATLAB command  will pass the value 45 into the variables m in the function file, and the output will be put into variable A.

The  symbol is used for note making in an M-file. The symbol tells MATLAB to skip the rest of the line. Comments should always be used in M-files to describe the function.

Loops can be made to run faster by preallocating output vectors or matrices. An example of this can be seen in the second line of the for loop where the matrix E is made one column larger for each iteration.

F = fun(6); D = zeros(6,50); For j = 1:50
 * D(:,j) = det(F^i);
 * End

Most of the MATLAB functions are built into the software, but some are M-files. To see a listing of any non built in M-file the MATLAB command type must be run.

Text strings, error messages, input
Text strings are inserted into MATLAB by surrounding the text with single quotes as shown below.

""

Typing this line in the MATLAB command window will assign the text string,, to the variable.

The MATLAB function  can be used to display various text strings. Two equivalent uses of this function are shown below.

disp('This is a text string') disp(a)

Displaying text strings can be used for many purposes, one of which is to display warnings or comments during the execution of M-files. In order to display errors during M-files, the  command is preferable. This is because the  command will abort the execution of the M-file. Proper implementation of the  command is shown below.

error('ERROR: Incorrect value!')

As with the  command, an identical implementation of the   command used above can be performed by assigning the text string to a variable and using that variable as the argument to the   command as shown below.

b = 'ERROR: Incorrect value!' error(b)

By using the  command in an M-file script, the execution of that M-file will pause while the prompting the user to input desired data. An example of a use of the  command is shown below.

""

When this line of code is reached in the M-file, the execution will pause while the prompt message is displayed on the screen. Once the user enters the desired data and presses the return key, the value entered will be assigned to the variable  and the M-file execution will continue.

Managing M-files
When working with an M-file in the local editor of MATLAB, often times it becomes necessary to switch back to the command window. In order to perform this maneuver, the command window must be kept active because if not, all of the variables would be lost in the switching process. A simple method for keeping the MATLAB command window open uses the !-feature. Placing a ! before any system command allows the user to fully execute that command without exiting the command window. An example of the !-feature is shown below.

""

In the above example, the file  will be opened, allowing the user to edit the M-file. Once  is closed, the user will be returned to the MATLAB command window exactly as it was left when the !-feature was used.

It is important to note that many operating systems permit multiple processes. In this case, it is much more efficient and user-friendly to simply open the local editor in a separate window than that of the command window. In this case, both windows can be left active, thus removing the risk of losing data stored in variables.

While editing M-files, debugging is a very important process that ensures code functionality. In order to debug an M-file with a filename of, the following syntax should be used.

dbtype file dbtype file start:end

In this example,  and   are user-specified line numbers in the M-file to debug between.

In order to determine the working directory at any time, use the  command as shown below.

>> pwd

To change the working directory, use the  command as shown below.

>> cd

Typing  or   in the command window as shown below will cause MATLAB to list the contents of the working directory.

>> dir >> ls

If it is desirable to only know which M-files exist in the working directory, the  command can be used as shown below.

>> what

In order to print the text of an M-file named  to the screen of the command window, the   command can be used as shown below.

>> type file.m

To delete an M-file named  from the disk, the   command can be used as shown below.

>> delete file.m

In order to work with M-files in MATLAB, the M-files must be located in a directory accessible to MATLAB. The easiest choice for directories is always the working directory, which is always accessible to MATLAB. To view a list of directories that are accessible to MATLAB, use the  command as shown below.

>> path

To add a new directory (e.g. ) to the list of directories accessible to MATLAB, use the variation of the   command shown below.

>> path(path,'c:\personal\mfiles')

Comparing efficiency of algorithms; flops, tic, toc
There are two ways in MATLAB to determine the efficiency of a given algorithm, the first being the amount of floating point operations (flops) performed and the second being the elapsed time from start to finish. To determine the amount of flops performed during an algorithm, the MATLAB function  can be used. For example, in order to count the number of flops performed in solving the linear system, $$F=ma$$, the proper implementation of the flops function is shown below.

flops(0), F=m*a; flops

is used prior to the start of the algorithm in order to set the count of flops to zero.

In order to determine the amount of time elapsed during the completion of the same algorithm, the functions  and   act as a stopwatch, with   being the start of the timer and   stopping the timer and displaying the elapsed time. The proper implementation of the functions  and   with the linear system, $$F=ma$$ is shown below.

tic, F=m*a; toc

It is important to note that using the elapsed time to determine the efficiency of an algorithm is not always accurate. This is due to the fact that the rate of execution of an algorithm is dependent on how busy the computer is with other processes at the time.

Output format
Although all calculations performed in MATLAB are carried out using double precision, it is possible to modify the format that is output to the command window using the following commands.

Once one of the output format commands are chosen, they remain in place until changed again by the user.

In order to fit more content on a page, the command  will remove most blank lines from the command window. The proper implementation of this command is shown below.

To reverse the compression caused by the command, use the command   as shown below.

Hard copy
Hard copy is a text-only format of the command window. The easiest way to access the hard copy format of the processes run in the MATLAB command window is to use the  command. Two proper usages of the  command are shown below.

>> diary file >> diary

The first example will save the hard copy format of the command window under the filename file in the working directory. The second example will save the hard copy format to the default filename of diary in the working directory. When the  command is invoked, it will record all text in the command window until the user types the   command. If the user would like to continue recording at a later time after the  command has been used, the   command needs to be entered in the command window.

Graphics
With MATLAB, the user can produce plots of planar curves, 3-D curves, 3-D mesh surfaces, and 3-D faceted surfaces. This section deals with each of these different plots, using the commands,  ,  , and  , respectively. The reader is encouraged to try the provided MATLAB to see the plots.

The 2-D Plot
First, the  command is demonstrated by graphing a sine function over the interval -4 to 4 as follows:

>> x = -4:.01:4; >> y = sin(x); >> plot(x,y)

This will produce a sine curve.

For another example, the graph $$y = e^{-x^2}$$ is produced over the interval -1.5 to 1.5 as follows:

>> x = -1.5:.01:1.5; >> y = exp(-x.^2); >> plot(x,y)

The period precedes the ^ in order to perform entry wise operations on the  vector.

The Figure Command
The command  can be used to produce an empty figure if the user desires. The most recently created figure will be considered the current figure by MATLAB, unless the user selects a different figure. This is done by typing the command, with the 1 designating the first created figure to be the one made current. The command  is used to return the number of the current figure.

The Fplot Command
If an M-file of a function has already been created, the command  can be used to quickly plot the graph of that function. As an example, one can create the M-File, with the contents of that function as follows:

function y = expnormal(x) y = exp(-x.^2);

Once this is saved, then typing

>> fplot('expnormal', [-1.5,1.5])

In the workspace will produce the same results as obtained in the  section above.

Parametrically Defined Curves
Plots of parametrically defined curves can be made as follows:

>> t = 0:.001:2*pi; x = cos(3*t); y = sin(2*t); plot(x,y)

Graph Labels
The following is a list of commands which take a string as their argument and the effect the command has on the current plot.

An example is:

>> title('Best Least Squares Fit')

Which will give the title  to the current plot.

To produce grid lines on the graph, the command  is used.

Changing Scales on Axes
While MATLAB auto-scales the axes, sometimes it is desired to customize the scales. This is done by using the following commands:

These commands are only valid after a plot is produced.

Producing Multiple Graphs on One Plot
One way of putting multiple graphs on one plot is as follows:

>> x = 0:.01:2*pi; y1 = sin(x); y2 = sin(2*x); y3 = sin(4*x); plot(x,y1,x,y2,x,y3)

This produces three sine waves on one plot. Another way to produce the same result is:

>> x = 0:.01:2*pi; Y = [sin(x)', sin(2*x)', sin(4*x)']; plot(x,Y)

Also, typing the command  will freeze the current graph so that another one can be entered on top of it, typing   will release the hold.

Line Types and Colors
There are many different line types and colors that can be used in MATLAB. They are as follows:

Line types: solid, dashed , dotted , dashdot Mark types: point, plus , star, circle, x-mark

Colors are chosen as follows:

Colors: yellow, magenta , cyan , red , green , blue , white , black

Thus, if a user wants a plot with a red dashed line, the command,

>> plot(x,y,'r--')

Should be used.

Specialized Commands
The  command will partition the plot screen into several small plots so that they can be seen all at once in the same figure, but on different plots. Other less used 2-D plotting functions are:,  ,  ,  ,  ,  ,  ,.

The 3-D Plot
The command  is used to produce 3-D curves in MATLAB. It works in basically the same way that the  command works for 2-D graphs.

A quick example of producing a 3-D plot follows:

>> t = .01:.01:20*pi; x = cos(t); y = sin(t); z = t.^3; plot3(x,y,z)

This produces a helix whose points are all the elements of x, y, and z. The vectors passed into the  command must all be the same length to work properly.

3-D Mesh and Surface Plots
3-D wire meshes are produced with the command  with   being a 2 dimensional matrix. An example is as follows:

>> mesh(eye(10))

The mesh surface is defined by the elements in the 2 dimensional matrix equaling the  coordinates of the mesh. Surface plots are similarly created with the command  as follows:

>> surf(eye(10))

To draw a mesh over a rectangle such as a graph of $$z = e^{-x^2 - y^2}$$ over the square  x , the following procedure is used:

>> xx = -2:.2:2; >> yy = xx; >> [x,y] = meshgrid(xx,yy); >> z = exp(-x.^2 - y.^2); >> mesh(z)

All 2-D formatting commands work for 3-D plots, so please reference that section.

Color and Shading
Color shading of 3-D plots is done using the  command. These are set by typing either:

,, or

Into the workspace, with a shading of faceted, interpolated, or flat being the result. The user is encouraged to experiment with all three in order to find which fits the graph best.

The color of the surface can be set with the  command, with the input argument being one of:

(default),,  ,  ,  ,  ,  ,  ,

Thus, the command  will result in a pink colormap.

Parametrically Defined Surfaces
The M-File below gives an example of how to plot a parametrically defined 3-D function:

function [x,y,z] = torus(r,n,a) % torus(r,n,a) generates a plot of a torus with a central % radius a and lateral radius r. n controls the number % of facets on the surface. These input variables are optional % with defaults r = .5, n = 30, a = 1. %    % [x,y,z] = torus(r,n,a) generates three (n+1)-by-(n+1) % matrices so that surf(x,y,z) will produce the torus. %    % See also SPHERE, CYLINDER if nargin < 3, a = 1; end if nargin < 2, n = 30; end if nargin < 1, r = .5; end theta = pi*(0:2:n)/n; phi = 2*pi*(0:2:n)'/n; xx = (a + r*cos(phi))*cos(theta); yy = (a + r*cos(phi))*sin(theta); zz = r*sin(phi)*ones(size(theta)); if nargout == 0 surf(xx,yy,zz) ar = (a + r)/sqrt(2); axis([-ar, ar, -ar, ar, -ar,ar]) else x = xx; y = yy; z = zz; end

Sparse Matrix Computations
Matlab has many functions that can speed up computation time if they are used when a matrix is sparse, in other words, many of the entries are zero. To demonstrate the matrix:

>> F = floor(10*rand(6)); F = triu(tril(F,1),-1);

is created. Next the statement:

>> S = sparse(F)

is used to convert  into sparse mode. This statement also returns the nonzero entries of  since the output is not suppressed.

>> F = full(S)

restores  to full storage, and the function   can be used to check whether a matrix is sparse or full.

However, sparse matrices are usually generated directly rather than through the sparse function. For example, a sparse tridiagonal matrix is created as shown below:

>> m = 6; n = 6; e = ones(n,1); d = -2*e; >> T = spdiags([e,d,e],[-1,0,1],m,n)

T =

(1,1)      -2       (2,1)        1       (1,2)        1       (2,2)       -2       (3,2)        1       (2,3)        1       (3,3)       -2       (4,3)        1       (3,4)        1       (4,4)       -2       (5,4)        1       (4,5)        1       (5,5)       -2       (6,5)        1       (5,6)        1       (6,6)       -2

Sparse Analogs
The sparse analogs of full matrix functions are as follows:

Operations With Sparse and Full Matrices
Since MATLAB's default storage is full matrix, if a sparse and full matrix are operated on together (such as in ), MATLAB will return a full matrix.

If the only matrices involved in the operation are sparse, the resulting matrix will be stored as sparse.

Contributing Team Members
The following students contributed to this report:

Andrew McDonald - Eml4500.f08.bike.mcdonald 22:11, 16 September 2008 (UTC)

Samuel Bernal - Eml4500.f08.bike.bernal 22:16, 16 September 2008 (UTC)

Shawn Gravois - Eml4500.f08.bike.gravois 22:22, 16 September 2008 (UTC)

Garrett Pataky - Eml4500.f08.bike.pataky 22:36, 16 September 2008 (UTC)

Eric Viale - Eml4500.f08.bike.viale 23:43, 16 September 2008 (UTC)

Bobby Sweeting - Eml4500.f08.bike.sweeting 19:38, 18 September 2008 (UTC)