User:Eml4500.f08.wiki1.aguilar/TeamHW1

EML4500 Fall 2008 Notes
These class notes cover lectures from the first day of class up to the material covered in the lecture of Friday, Sept. 5th 2008. Brooks Handy is this section's primary author.

Syllabus
{| class="toccolours collapsible collapsed" width=100% ! colspan="2" |

 EML 4500 Finite Element Analysis and Design (FEAD) [http://clesm.mae.ufl.edu/wiki.pub/index.php/Main_Page |Dr. L. Vu-Quoc|] Fall 2008



Course description
Fundamentals of the finite element (FE) method and applications to structural, solid, and bio-mechanics. Principle of virtual work. Derivation of the stiffness matrices for truss, beam, and solid elements. Coordinate transformation for structural elements in 3-D. Direct stiffness method. Static analysis of FE systems with a matrix linear algebra approach, internal structure of a FE code, coding and plotting. Linear stability analysis of truss and beam structures. Applications to aerospace structures and biomechanics. Other topics such as axisymmetric solid elements, dynamic analysis, substructuring analysis, etc. could be taught, depending on the class and the instructor.

Course objective
This course is intended to be the first Finite Element Method (FEM) course for all engineering students. Its objective is to develop a basic understanding of the fundamentals of the FEM through careful derivation of the stiffness matrix from first principles. Fundamental concepts of linear algebra are taught, e.g., inversion and transpose of matrix product, matrix partitioning and solution by static condensation, determinant, eigenvalue problems, etc. For trusses and beams, coordinate transformation of the degrees of freedom from local to global coordinates and the direct stiffness method to assemble element matrices into global matrix is emphasized. The 3-D aspect is emphasized for all truss and beam elements. Euler-Bernoulli beam theory with shear correction, in 3-D, is taught in detail. The connection of linear algebra to the FEM is emphasized, e.g., rigid-body modes and the singularity of the element stiffness matrix. For solid elements, an introduction to the principle of minimum potential energy and the principle of virtual work taught. Commercial codes can be used to train students on practical aspects of FE analysis. Some aspects of buckling analysis and dynamic analysis, and their connection to linear algebra, are addressed.

Topics
* 3-D truss, beam, and solid structures. Beams with shear correction. * Matrix algebra and its application to finite element solution. * Construction of a FE code, coding and plotting. * Linear stability (buckling) analysis of truss and beam structures. * Applications to mechanical and aerospace engineering, biomechanics, and other engineering    areas (e.g., circuit analysis, heat conduction, etc.) * Class projects: Students will "design" and solve open-ended problems that involve FE model    building and analysis of complex problems (e.g., prostheses, organs, airframes, automobiles,     off-shore platforms, etc.). * Other advanced topics: axisymmetric solid elements, dynamic analysis, nonlinear analysis,    substructuring analyis, etc. depending on mutual interest between the students and the     instructor.

Text and Other Resources
M. Asghar Bhatti, Finite Element Analysis With Mathematica and Matlab Computations and Practical Applications: Fundamental Concepts John Wiley & Sons (February 4, 2005) ISBN: 0471648086 Fri, 07 Jul 2006.

Recommended
* J.S. Przemieniecki, Theory of Matrix Structural Analysis, Dover, 1985, (McGraw-Hill, 1968). ISBN 0-486-64948-2 (Paperback). Library call no. 624.171 P973t. * Y.W. Kwon and H. Bang, Finite Element Method using MATLAB, 2nd edition, CRC Press, 2000. ISBN 0-8493-9653-0. Library call no. TA347.F5 K86 1997 (first edition). * Matlab Guide to Finite Elements: An Interactive Approach, Peter Issa Kattan, Springer Verlag   (February 15, 2003), ISBN: 3540438742.

Web pages of related courses
Fall 2006: EML 4500 Finite Element Analysis and Design. Fall 2003: EML 4500 Finite Element Analysis and Design. Spring 2000: EAS 4210C Finite Element for Engineering Mechanics Spring 1999: EAS 4210C Aerospace Structures 2

Grade determination:
Tentatively, homework/project and class participation including bonuses (31%), exam1 (23%), exam2 (23%), exam3 (23%). Adjustments to the weights could be made at the end of the course.

Homework:
There will be HW assignments, which are to be solved following Cooperative Learning Techniques. HW should be thought of as mini projects, which include "hand solution" with the help of Matlab and the use of the Matlab codes that come with the textbook. Students will also be asked to develop their own Matlab codes. For a tutorial on how to use Matlab, see [|Matlab] matters. See the [|course policy] for more details.

Course outcome:
Upon a successful completion of this course, a student is expected to: The above outcomes are consistent with the Departmental and College of Engineering Educational Objectives and meet the following ABET criteria:
 * 1) Have an understanding of matrix linear algebra and its role in the solution of FE systems.
 * 2) Master the derivation of various structural elements in 3-D (truss, beam), and the associated transformation of the stiffness matrix from local coordinates to global coordinates by the Principle of Virtual Work.
 * 3) Know how to correct for shear deformation in Euler-Bernoulli beam.
 * 4) Have a notion of the derivation of the stiffness matrix of solid elements, and their use in a commercial FE code.
 * 5) Know that the concepts of the FEM are also applied to fields other than structural and solid mechanics, e.g., circuit analysis, heat conduction, fluid mechanics, electromagnetics, etc.
 * 6) Develop skills to tackle open-ended problems in FE analysis and design.
 * 7) Develop communication skills, presentation skills, report-writing skills, team work (cooperative learning).
 * 1) Ability to apply knowledge of mathematics, science, and engineering.
 * 2) Ability to identify, formulate, and solve engineering problems.
 * 3) Ability communicate effectively.
 * 4) Ability to use the techniques, skills, and modern engineering tools necessary for engineering practice.

This page was last updated on: Tue, 12 Aug 2008, 17:56:54 EDT


 * }

Class Structure
The class is structured to focus on teamwork. Everyone in the class is broken up into groups of 5-6 members. In order to facilitate members working together, Wikiversity plays a vital role in assignments and projects.

Through Wikiversity, the members are able to access other group members information and everyone is able to work on an assignment or project. Wikipedia and class guidelines provide for a safe and effective method for project submittal and significantly reduce the chances of data loss.

Labeling Conventions
Bar Element 1: Global Free-Body Diagram

The structure should be labeled using numbers in triangles to identify elements, numbers in circles to identify global nodes, and numbers in squares to identify local nodes (in local free body diagrams). Draw free body diagrams to identify all forces and reactions. Draw a free body diagram for each element. Identify forces using Fie to describe the ith internal force on element e. Identify displacements with die using the same labeling convention.

Describe elements as springs
Next we must understand that each element can be described as a spring, under force F, displacement d, and with a spring constant K. The governing equation is then F=Kd. When considering a spring with 2 free ends, it can be analyzed using a matrix equation F=Kd.

6 Steps of the FEM
The Finite Element Method (FEM) is a six step process. The first step is to draw a global picture at a structural level including the global degrees of freedom (DOF) and global forces. The displacement DOFs can be partitioned into a known part (constraints) and an unknown part (must be solved using FEM). The global forces can also be partitioned into a known part (applied forces) and an unknown part (reactions). The second step is to draw individual element pictures including DOFs and forces in either the global coordinate system, or a local coordinate system. The third step is determine the global force-displacement relationships. Assemble the element stiffness and force matrices using global coordinates in the form Kd=F where K is a nxn matrix, d is a nx1 matrix, and F is a nx1 matrix. The fourth step is to eliminate the known DOFs. The stiffness matrix is non-singular and therefore invertable. We reduce the equation to  d = K -1 F . The fifth step is the compute the element forces from the known d and determine the element stresses. The sixth step is to compute the reactions.

MATLAB Tutorial
This section is based on the MATLAB primer tutorial that was written by Mermit Sigmon of the University of Florida. This section had multiple primary authors and was separated as follows: Sections 1-5: Bryan Ambrosio Sections 6-9: Michael Aguilar Sections 10-12: Lyndsey Schaet Sections 13-17: Clayton Brannon Sections 18-19: Benjamin Oatley

{| class="toccolours collapsible collapsed" width=100% ! colspan="2" |

 Sections 1-5

Section 1 How to Access MATLAB
After logging onto a computer with MATLAB installed, run the system command matlab or click on the desktop icon. To exit MATLAB, enter quit or exit in the MATLAB command window, or click on the File menu and select Exit MATLAB.

When the Editor in MATLAB is opened, it is convenient to have the Editor and Command windows opened separately. The specifics of the Editor are covered later on in this tutorial.

Section 2 Entering Matrices
MATLAB is based around operating with matrices. In fact, MATLAB is an abbreviation for Matrix Laboratory. The program can interpret these matrices as either scalars or vectors.

Matrices can be created by entering an explicit list of elements, generating built in statements and functions, creating a disk file with a local editor, or loading external data files or applications.

The following are all examples for creating matrix A, which is a 3x3 matrix. A = [1 2 3; 4 5 6; 7 8 9]

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

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

Notice that the elements in the rows of the matrix can be separated by commas or blank spaces.

The following is an example of how to enter a number in exponential form.

x = 2.34e-9

Notice when the number in entered, there are no spaces in between the e.

MATLAB is capable of doing computations with complex numbers. The following are examples of how to create complex matrices.

A = [1 2;3 4] + i*[5 6;7 8]

A = [1+5i 2+6i;3+7i 4+8i]

Notice when the complex numbers were listed inside the matrix, no blank spaces were used. It should also be noted that either i or j can be used as the imaginary unit. Also, if i or j are assigned as variables to represent a new value, they will not retain their value as an imaginary number. For example if the user enters the command

i = 5

then i will no longer be equal to 'sqrt(-1)', it will be equal to 5.

If a large matrix must be entered, creating an ASCII file is a good option because it can make it easier to correct errors. If an ASCII file is created and named data.ext, simply type load data.ext into the MATLAB command line and press enter. This command will read the file and save it as the variable data. MATLAB also has built in functions such as rand, magic, and hilb. If rand(n) is typed into the command line, MATLAB will create a n x n matrix with randomly generated numbers distributed uniformly between 0 and 1. If rand(m,n) is typed into the command line, MATLAB will create a m x n matrix with the same criteria as before. If magic(n) is typed into the command line, MATLAB will create an integral n x n matrix which is a magic square. This means all the rows, columns, and diagonals have a common sum. If hilb(n) is typed into the command line, MATLAB will create a n x n Hilbert matrix.

Individual entries in a matrix can be easily referenced. For example,

A(2,3)

selects the value in the second row, third column of matrix A. Also

X(3)

Would select the third coordinate of vector X.

Section 3 Matrix and Array Operations
The following matrix operations are available in MATLAB:

+	addition -	Subtraction ^	power ‘	conjugate transpose \	left division /	right division
 * multiplication

Since a scalar value entered into MATLAB is stored as a 1 x 1 matrix, these operations also apply to those values. If MATLAB is told to perform an operation that is not possible for a specific matrix, an error message will appear on the screen.

Matrix division can sometimes be confusing in MATLAB. The difference in right and left division is shown below.

x = A\b is the solution of A*x = b

x = b/A is the solution of x*A = b (another way of writing this could be x = (A’\b’)’ )

It is also important to note that addition and subtraction operate entry wise, but multiplication, power, and left and right division operate as matrix operations. These matrix operations can operate as entry wise operations by placing a period in front of them. An example is

[1,2,3,4].*[1,2,3,4]	or 	[1,2,3,4].^2

Both of these operations will give [1,4,9,16] as the solution.

Section 4 Statements, Expressions, and Variables and Saving Sessions
MATLAB uses expression language. This means when values are typed in, they are entered in the form of variable = expression or just as expression. For example,

x = 5*4

The evaluation of this expression is created as a matrix and displayed on the screen, such as

x = 20

If a variable and equal sign are not used, the result is automatically saved as the variable ans.

The user can also decide to continue the statement to the next line by using three or more periods (…) followed by enter, or several statements can be placed on a single line by separating them with commas (,) or semicolons (;).

If the variable is rather large, it may be useful to suppress the statement. By placing a semicolon (;) at the end of a statement, the assignment is carried out, but the result will not be printed on the screen.

It is also important to note that MATLAB is case sensitive. For example, alpha is not the same as Alpha.

In order to see a list of variables that are currently being used in the workspace, type who (or whos) in the command line. If a variable needs to be cleared from the workspace, enter clear variablename'. If clear is entered into the command line, all nonpermanent variables will be cleared.

If the unit round off needs to be changed, type in eps (epsilon) to have MATLAB use a round off of 10^-16. This can be useful in specifying tolerances for convergence of iterative processes.

Sometimes a computer will enter a loop that does not stop or takes too long to calculate. These computations can be stopped in MATLAB by pressing CTRL-c.

When MATLAB is closed, all of the variables in the workspace are deleted. If these variables need to be saved, enter save in the command line before closing the program. These variables are written to a disk file named matlab.mat. When MATLAB is started again, enter the command load and the variables will be restored to the workspace.

Section 5 Matrix Building Functions
The following are convenient matrix building functions:

eye		identity matrix zeros 		matrix of zeros ones		matrix of ones diag		create or extract diagnols triu		upper triangular part of a matrix tril		lower triangular part of a matrix rand		randomly generated matrix hilb		Hilbert matrix magic		magic square toeplitz	see help toeplitz

For example, zeros(m,n) creates a m x n matix of zeros, and zeros(n) produces a n x n matrix of zeros. If A has already been defined as a matrix, then zeros(size(A)) will create a matrix of zeros that is the same size as matrix A.

If x has already been defined as a vector, diag(x) creates a diagonal matrix with x down the diagonal. If A has already been defined as a square matrix, then diag(A) creates a vector consisting of the diagonal of A.

Matrices can also be built from blocks consisting of other matrices. For example, if A is defined as a 3 x 3 matrix, then B = [A, zeros(3,2); zeros(2,3), eye(2)] will be 5 x 5 matrix.


 * }

{| class="toccolours collapsible collapsed" width=100% ! colspan="2" |

 Sections 6-9

Section 6 For, While, If, and Relations
As with other computer programming languages, MATLAB has the flow control statements For, While, If, and Relations.

For
For loops are started with the command. For example, one of the most simple examples of a for-loop is:

for j=1:4, j end Here, a loop is cycled through, setting the variable j to 1, then 2, then 3, and then 4, and showing each of these outputs in the command window.

Another example, for a given "n", the statement: x=[]; for i=1:n, x=[x,i^2], end which is the same as x=[]; for i=1:n x=[x,i^2] end will produce a certain "n" vector. The statement, x=[]; for i=n:-1:1, x=[x,i^2], end produces the same vector but in the reverse order.

The statements for i=1:m for j= 1:n H(i,j) = 1/(i+j-1); end end H generate an m-by-n Hilbert matrix.

Note: Using the semicolon in the code stops MATLAB from printing unwanted intermediate results.

MATLAB allows for any matrix to be used in place of 1:n. The variable just consecutive assumes the value of each column of the matrix.

While
While loops are done in the exact same way using the command. The general form of the  loop is:

relation


 * statements



As expected, the  loop will continue to be executed as long as the relation remains true.

A basic  loop example is given below. n=0; while n<5 n=n+1; n end This loop cycles through, increasing the variable n by 1 until the relation is no longer true.

If
The  command allows for various if-then statements to be executed. The general form of the  loop is:


 * relation


 * statements



As expected, the  command executes only when the relation is true.

A basic  command example is given below. n=0; if n==0 n=2; n end Here, we set n=0, so the relation is true and theprint statement exectues accordingly. If the code was repeated, n would now be equal to 2, so nothing would be printed.

Multiple branching is also possible. This is done with  and   commands, as shown below. n=x; if n>0 m='Positive'; elseif n<0 m='Negative'; else m='0'; end

We can see how the output changes depending on the value of x.

Relations
MATLAB uses typical programming relationship operators: <    less than >    greater than <=   less than or equal to     >=    greater than or equal to     ==    equal ~=   not equal Note: The assignment statement "=" is different from the "==" relationship operator.

You can also use these logical operators in conjunction with the relationship operators: &    and |    or     ~     not

When applied to scalars, the relation is the scalar 1 if the relation is true, and 0 if the relation is false. For example, executing 1<2 prints "ans = 1", however, if you enter 2<1, the result is "ans = 0".

These relationship operators can also be applied to matrices. If the are the same size, the output is a matrix of 0's and 1's giving the value of the relation between corresponding entries.

Note: if you wish for a statement to be executed if matrices A and B are equal, you could type:

if A == B  statement end

but the seemly obvious opposite below would not execute as expected:

if A ~= B  statement end This statement would only execute if each of the corresponding entries was different. So, alternatively, to execute a statement from two matrices that were even one entry different, you would use:

if A == B else statement end

Section 7 Scalar Functions
Many MATLAB functions are used mainly on scalars. A list of the most common include: sin            asin             exp                    abs               round cos            acos             log (natural log)      sqrt              floor tan            atan             rem (remainder)        sign              ceil

Note: The operate element-wise when applied to a matrix.

Section 8 Vector Functions
Other MATLAB functions operate essentially on a vector (row or column), but act on an m-by-n matrix (m$$>=$$2) in a column-by-column fashion to produce a row vector containing the results of their application to each column.

For example: m=[1,3;2,4]; mean(m) gives the result: ans =

1.5000   3.5000 As you can see, the mean of 1 and 2 is 1.5 and the mean of 3 and 4 is 3.5.

This means that in order to find the maximum entry in a matrix A, we use max(max(A)) rather than max(A).

Note: Row-by-row action can be obtained by using the transpose; for example, mean(B')'.

Some of these vector functions are listed below: max         sum          median          any min         prod         mean            all sort                     std

Section 9 Matrix Functions
MATLAB is especially useful when using any of its various matrix functions. Some of the most useful include: eig      eigenvalues and eigenvectors chol     cholesky factorization svd      single 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, infinite-norm cond     condition number in the 2-norm rank     rank

Note: Some of these functions may have single or multiple output arguments. While  produces a column vector containing the eigenvalues of A,   produces a matrix U whose columns are the eigenvectors of A and a diagonal matrix D with the eigenvalues of A on its diagonal.

For example, if m=[1,2,3;4,5,6;7,8,9], then [u,d] eig(m) outputs:

u =

-0.2320  -0.7858    0.4082        -0.5253   -0.0868   -0.8165        -0.8187    0.6123    0.4082

d =

16.1168        0         0              0   -1.1168         0              0         0   -0.0000
 * }

{| class="toccolours collapsible collapsed" width=100% ! colspan="2" |

 Sections 10-12

Section 10 - Command Line Editing and Recall
This section discusses the ease of editing commands using the arrow keys on the keyboard and recalling command lines in Matlab without having to write M-files (section 12).

Editing commands is easy in Matlab. The cursor can be placed anywhere in the command line using the mouse, left/right arrow keys, and backspace. This simple method of editing does not exist in other programming languages such as Fortran. On the PC's that most of us use, the Home, End, and Delete keys can also be used to place the cursor to make revisions. Using the up/down arrow keys allows the user to scroll through past command lines. This allows the user to simply copy and paste a command they want to use again. Once pasted, the user can also alter the command line. This is very useful if you were using a long linear regression equation and only one constant or variable needed to be replaced.

Section 11 - Submatricies and Colon Notation
This section covers the use of colon notation for matricies. It also discusses subscripting by integral vectors. Both of these methods are used to easily manipulate complicated vectors and submatricies. Creative use of the colon notation discussed here can often eliminate the need for loops thus making the execution of MATLAB code faster.

Vectors typically seen as [a b c d e f....n] can take on the notation of [a:n] in Matlab. Using this colon notation makes it easier and simpler to read and execute. One example of the use of this expression 1:5. This expands out to the row matrix [1 2 3 4 5]. When using this notation, the vector does not need to increment by just one either. Adding a middle term defines what level the vector should increment. For example, the expression 0.2:0.2:1.2 is the vector [0.2 0.4 0.6 0.8 1.0 1.2]. Another example is the expression 5:-1:1 gives [5 4 3 2 1].

The colon notation makes it easy to access submatricies as well as alter a given matrix. Below are some examples.

If A is a predefined matrix of arbitrary size n by n, the notation A(1:4,3) is the column vector consisting of the first four entries of the third column of A.

Using the colon by itself takes an entire row or column from a given matrix, in this case the matrix A. For example, the expression A(:,3) is the entire third column of A. The expression A(1:4,:) is the first four rows of A.

Creating new matricies using arbitrary integral vectors also proves useful in Matlab. The expression A(:,[2 4]) is a matrix whose two columns consist of column 2 and 4 of A. This method of manipulation can also be used in an assignment statement. One example of this is the expression A(:,[2 4 5]) = B(:,1:3) replaces columns 2, 4, and 5 of A with the first three columnds of B. Running this command prints and assigns the entire altered matrix A.

This notation also makes multiplying matricies easier. The expression A(:,[2,4]) = A(:,[2,4])*[1 2;3 4] multiplies the columns 2 and 4 in matrix A by the 2x2 matrix [1 2;3 4]. Running this command once again prints the entire altered matrix.

By comparison to other coding languages, using this notation makes adds to Matlab's usefulness when dealing with vectors and matricies.

Section 12 - M-files
M-files are MATLAB files with the ".m" file extension. These are usually created with a local editor, and contain a sequence of statements that can be executed. There are two types of M-files, script files and function files.

Script Files
A script file consists of a sequence of normal MATLAB statements. For example, if you create a script file called, then typing   into the command window will execute the statements that are in the script.

Note: Variables used in scripts are global and will interfere with any variables of the same name within the current MATLAB session.

Function Files
Function files allow you to create your own functions specific to what you are trying to do, and these will have the status as any other function within MATLAB. Function file variables are local by default, but can be set as global.

Example: function a = randint(m,n) %RANDINT Randomly generated integral matrix. %randint(m,n) returns an n-by-m matrix with integers between 0 and 9 a = floor(10*rand(m,n));

You would save this code as a diskfile with the name. Notice that the first line of code gives the name of the function, the input arguments, and output arguments; this line is the difference between a script file and a function file.

You would execute this function file by entering. This sends  and   to be sent as   and   respectively with the output result set as. Again, these variable are, by default, local variables.

The function are flexible in their use of inputs and outputs. The use of, ("number of input arguments") allows you to set a default value of an omitted input variable. A function may also have multiple output arguments.

To make comments, use '%' and the rest of the line is ignored by MATLAB. It is considered correct to include some beginning comment lines to describe the use of the function, and can displayed for example if  is entered. You should also try to write in efficient code, using vectorized operations and avoiding loops. If  loops must be used, you can make them faster by pre-allocating any vectors or matrices to which the output is stored.

Some MATLAB functions are built in while others are distributed as M-files. A listing of non-built-in functions can be seen with the MATLAB command  functionname.


 * }

{| class="toccolours collapsible collapsed" width=100% ! colspan="2" |

 Sections 13-17

Section 13 Text Strings, Error Messages, Input
Text strings can be entered into MATLAB using single quotation marks as follows:

string='text string'

Using the disp function, text strings can be displayed in the following way:

disp('displays text string')

Error messages can be displayed with the error function:

error('error message')

which is useful with M-files, as an M-file execution will be aborted.

Within M-files, the user may be prompted to input data using the input function:

variable=input('Enter number: ')

The variable is assigned the input value and execution continues.

Section 14 Managing M-files
Creating or editing an M-file from within MATLAB can be accomplished using the !-feature. This is useful because all variables would be reset upon exiting MATLAB. System sommands such as copying, editing, and printing can be executed using this feature. As an example, !ed can be used to access the system editor:

>> !ed fileforediting.m

After editing the file, the user will return to MATLAB as it was before entering the editor.

In addition, the editor and MATLAB may be active simultaneously on systems permitting multiple processes, suspending one while working in another.

Debugging tools can be seen using the help dbtype command.

The present working directory can be viewed with the pwd command and cd can be used to change directories. The dir and ls commands list the contents of the directory and what lists the M-files within the directory only. The delete command deletes a diskfile. The type command prints a M-file to the screen.

M-files must be stored in a MATLAB-accesible directory, such as the present working directory. Typically, these files are stored in a subdirectory of the home directory titled matlab.

Section 15 Comparing Efficiency of Algorithms: Flops, Tic and Toc
Efficiency can be measured by counting the floating point operations (flops)performed or the elapsed time.

The flops count is reset using flops(0). Using the command flops again immediately after the operation gives the flops count.

flops(0), var=2+2; flops

The time elapsed for any given command can be measured using the tic command immediately before the command and toc just after it.

tic, command, toc

The processing speed available for the operation will also affect these measurements.

Section 16 Output Format
Computations within MATLAB are performed using double precision, though the format with which the results are shown can be changed with the following commands:

format short          fixed point with four decimal places (default) format long           fixed point with fourteen decimal places format short e        scientific notation with four decimal places format long e         scientific notation with fifteen decimal places format rat            approximation by ratio of small integers format hex            hexadecimal format format bank           fixed dollars and cents format +              +, -, blank

Changes to format remain until changed again.

Section 17 Hardcopy
Hardcopy is obtained using the diary command. The command below causes text that appears subsequently on the screen to be written to the named diskfile (default: diary):

diary named diskfile

The command diary on will write text to the file until the command diary off is called.
 * }

{| class="toccolours collapsible collapsed" width=100% ! colspan="2" |

 Sections 18-19

Section 18: MATLAB Graphics
One of the functions of MATLAB is the ability to produce several different types of curves and plots. *These include the following, followed by their respective commands:

planar plots of curves		                       plot 3-D plots of curves				       plot3 3-D mesh surface plots				       mesh 3-D faceted surface plots				surf

Planar Plots
For example, to plot a cosine function over the interval -5 to 5 on an x-y plot of the elements of x versus the elements of y, the command is as follows:

x = -5 : .01 : 5 y = cos(x) plot(x,y) Another example of a sample function would be to plot the function y=e^(x^3 )over the interval of -3.5 to 3.5 on an x-y plot of the elements of x versus the elements of y, the command is as follows: x = -3.5 : .01 : 3.5 y = exp(x.^3) plot(x,y)

“fplots”
The function “fplot” allows the user to graph a function with great ease and efficiency. To plot the above function, the function must first be defined in an M-file (e.g. “expnormal.m”). The M-file for the above function would read as follows: function y = expnormal(x) y = exp(x.^3) followed by the command fplot(‘expnormal’, [-3.5,3.5])

Parametric Curves
Parametric curves can be created in MATLAB. The commands for an example parametric function are as follows: t = 0: 0.01: 2*pi x = sin(5*t) y = cos(3*t) plot(x,y) MATLAB graphs can be assigned with titles, labeled axes, as well as text placed within the graph. These options with their respective commands are as follows: graph title					title x-axis label					x label y-axis label					y label place text on graph using mouse		       gtext position text on coordinates			text For example, to assign the label “Force (N)” to the x-axis, the appropriate command would be as follows: xlabel(‘Force (N)’)

Axis Reformatting
MATLAB automatically formats the axes of graphs with an auto-scale. The command “axis” following the “plot” command can override this auto-scale. Some additional options with their respective commands are as follows: set axis scale to prescribed limits			axis([xmin, xmax, ymin, ymax]) freeze scale for subsequent graphs			axis(axis) return to auto-scale					axis auto returns vector v showing current scale		       v = axis same scale on both axes				       axis square same scale and tic marks on both axes		       axis equal turn off axis scaling and tic marks			axis off turn on axis scaling and tic marks			axis on

Superimposing Plots on Top of Each Other
In MATLAB it is possible to place multiple plots on a single graph. One example of such a case is listed in the following commands: x = 0: .01: 2*pi y1 = cos(x) y2 = cos(3*x) y3 = cos(5*x) plot(x,y1,x,y2,x,y3) The same plots can be generated using a matrix Y, as follows: x = 0: .01: 2*pi Y = [cos(x)’, cos(3*x)’, cos(5*x)’] plot(x,Y) Another way to superimpose plots on each other is with the command “hold”. “hold on” will freeze the current plot and will superimpose subsequent plots on it. “hold off” will release the specified hold.

Overriding Default Linetypes, Pointtypes, and Colors
One example of overriding defaults for a dotted line and a line with circles placed at each node is as follows: x = 0: .01: 2*pi y1 = cos(x) y2 = sin(3*x) plot(x,y1, ‘:’,x,y2, ‘o’) Options for linetypes includes the following: solid (-) dashed (--) dotted dashdot (-.) Options for marktypes include the following: point (.) plus (+) star(*) circle (o) x-mark (x) Options for colors include the following: yellow (y) magenta (m) cyan (c) red (r) green (g) blue (b) white (w) black (k) For example, to plot a blue dotted line, the commands are as follows: plot(x,y,’b:’)

Graphics Hardcopy
With the command “print”, MATLAB will send a high-resolution copy of the current graphics figure to the computer’s default printer. The command “printopt” specifies the default setting used the by the “print” command. The command “print filename” saves the current graphics figure to the specified filename. 3-D Line Plots MATLAB can also create curves in three dimensions with the command “plot3”. For example, a parametric graph in three dimensions can be created with the following commands: t = .01: .01: 2*pi x = sin(2*t) y = cos(t) z = t.^2 plot3(x,y,z)

3-D Mesh and Surface Plots
The command “mesh” creates a three-dimensional wire mesh surface plot.

The command “surf” creates a three-dimensional faceted surface plot.

For example, the graph of z=e^(y^3+x^2 )over the square [-3,3] x [-3,3] can be created with the following commands: xx = -3: .1 :3 yy = xx [x,y] = meshgrid(xx,yy) z = exp(y.^3 + x.^2) mesh(z)

Color Shading and Color Profile
The command “shading” edits the color shading of different surfaces in MATLAB. The three settings and their respective commands are as follows: faceted (default)		shading faceted interpolated			shading interp flat				shading flat Color profiles in MATLAB can also be edited using the command “colormap”. Possible colormap options include the following: hsv (default) hot cool jet pink copper flag gray bone For example, to set the color profile of a figure to hot, the command is as follows: colormap(hot)

Section 19: Sparse Matrix Computations
MATLAB has the capability of significantly reducing the computation time in regards to solving matrices. MATLAB has two storage modes, full (default) and sparse.

For a matrix A, the command “nnz(A)” would return the number of nonzero elements in matrix A.

To create a sparse matrix, the necessary commands are as follows: m = 5 n = 5 e = ones(n,1) d = -2*e T = spdiags([e,d,e], [-2,0,2], m, n) The sparse analogs of eye, zeros, ones, and randn are as follows: speye sparse spones sprandn The command “sparse” allows for the generation of a sparse matrix from the listing of its nonzero entries. i = [1 2 3 5 5 5] j = [1 2 3 3 2 1] s = [2 3 4 5 6 7] S = sparse(i, j, s, 4, 3), full(S) The command “sparse(i, j, s, m, n) is made up of several components. i and j list the row and column indices and s lists the nonzero entries of S. m and n are the dimensions of the matrix S.
 * }

Authors
Michael Aguilar Eml4500.f08.wiki1.aguilar 00:44, 23 September 2008 (UTC) Bryan Ambrosio Eml4500.f08.wiki1.ambrosio 14:36, 18 September 2008 (UTC) Clayton Brannon Eml4500.f08.wiki1.brannon 01:06, 18 September 2008 (UTC)

Benjamin Oatley Eml4500.f08.wiki1.oatley 21:22, 17 September 2008 (UTC)

Lyndsey Schaet Eml4500.f08.wiki1.schaet 17:49, 19 September 2008 (UTC)