- 1 EML 4500: An Introduction
- 2 Chapters 1 & 4 - Methods for Solving Simple Trusses using the Matrix Method
- 2.1 Solving Trusses: Method of Broken Elements and Free Body Diagrams when solving Example Problem 1.1
- 2.2 Linear Springs
- 2.3 The Stiffness Matrix
- 2.4 Developing a "Recipe" to Simplify Problem Solving
- 2.5 Statically Determinate: Problem 1.2
- 2.6 Statically Indeterminate: Problem 1.3
- 2.7 Working with Element Equations, Solutions and Plane Trusses,
- 3 Matlab Primer
- 3.1 Introduction
- 3.2 1.Accessing MATLAB
- 3.3 2.Entering Matrices
- 3.4 3. Matrix operations, array operations
- 3.5 4. Statements, expressions, and variables, saving a session
- 3.6 5. Matrix building functions
- 3.7 6. For, while,- and relations
- 3.8 7. Scalar Functions
- 3.9 8. Vector Functions
- 3.10 9. Matrix Functions
- 3.11 10. Command Line Editing and Recall
- 3.12 11. Submatrices and Colon Notation
- 3.13 12. M-files
- 3.14 13. Text Strings, Error Messages, Input
- 3.15 14. Managing M-files
- 3.16 15. Comparing efficiency of algorithms: flops, tic and toc
- 3.17 16. Output Format
- 3.18 17. Hardcopy
- 3.19 18. Graphics
- 3.20 19. Sparse Matrix Computations
- 3.21 20. Reference
- 4 Contributing Members
EML 4500: An Introduction
The University of Florida course EML4500 Finite Element Analysis and Design (FEAD) will emphasize an understanding of the Finite Element Analysis method and its applications when working with structural, solid, and bio-mechanics. During this course we will work with 3-D truss systems, beams and solid structures. To help solve these systems, we will use matrix algebra and its application to the finite element model, along with a finite element codes derived in MATLAB to provide for a complete analysis of the truss and beam structures. Fundamental concepts of Liner Algebra are also taught along with coordinate transformations. The Finite Element Method (FEM) will be employed in order to solve the Partial Differential Equations that govern aerospace structure mechanics. FEM is also widely used to solve other challenges in engineering and applied math. A specific example is the use of FEM to aid in the exploration of oil reservoirs.
Throughout the semester there will be many resources implemented that will encourage learning through lecture notes, assigned readings, cooperative learning assignments as well as in class exams.
Course Website: [FEAD 4500 Course Homepage]
TA #1 : Nicolas Vigroux
TA #2: Sung-Uk Zhang
|Required Course Textbook|
|Recommended Course Textbooks|
Theory of Matrix Structural Analysis, J.S. Przemieniecki. Dover, 1985, (McGraw-Hill, 1968). ISBN-10: 0486649482 [Source: Amazon.com]
Finite Element Method using MATLAB, Y.W. Kwon and H. Bang. 2nd edition, CRC Press, 2000. ISBN-10: 0849396530. [Source: Bestwebbuys.com]
Matlab Guide to Finite Elements: An Interactive Approach, Peter Issa Kattan and Springer Verlag. February 15, 2003. ISBN-10: 3540438742 [Source: Bestwebbuys.com
Cooperative Learning Method: Our Vision
|Cooperative Learning Technique|
First, students were required to form groups of five to six students with a team name of four to six characters, and nominate one group memeber to serve as a team coordinator. It is the responsibility of this team member to coordinate communication and information between the professor and the rest of team members within the group. Students are also required to exchange contact information such as their email addresses, UFID numbers and telephone numbers. After contact information is exchanged between members, the team coordinator is responsible for emailing the instructor and providing a roster of the group complete with all of their contact information. The next step is for each team member to also begin setting up their individual wikipedia accounts for their class assignments and participation, described below, (Wikipedia Requirements: User Accounts). The items below highlight the advantages and different details that concern the cooperative learning technique. Much of what is described is only a synopsis of what is described through a workshop Effective Teaching by R.M. Felder and R. Brent.
|Wikipedia Requirements: User Accounts|
To begin setting up group user accounts, login to wikipedia.com and setup a wikipedia username with the following format: course_number.semester.team_name.last_name. An example of a username is: eas4200c.f08.gators.bert, where <eas4200c> is the course name, <f08> refers to the Fall 2008 semester, <gators> is the team name and <bert> is the last name of the specified group member. It is important to note that in line with some of Wikipedia's policies, username space pages are NOT Wikipedia articles and help preserve confidentiality of all users alike. For this portion of the class, contributions made from each group memeber will be written to Wikiversity rather than Wikipedia, due to the fact that the vision of Wikiversity promotes learning resources and projects for all educational levels. By creating unique and distinct usernames, group members will be able to publish their HW articles to the web, collaborate with their group members, evaluate group member participation, as well as filter out any saboteurs. For the purpose of this class and with the creation of the wikipedia user accounts, group members will only be allowed to edit their specific articles that pertain to the course work, and not other articles on Wikiversity or Wikipedia. After the creation of all group member usernames, our group, Team Aero, was required to choose one of the following Wiki Browser/Editing Programs:
|Homework Submission Policies and Guidelines|
When compiling Homework reports it will be important to refer to the notes taken in class so that extended contributions can be made from group members, while paying particular attention to all of the details covered. Information obtained from other resources such as your text is encouraged, however it should be done only with proper reference. Problems discussed in lecture should be neatly restated, with a method of solution provided. If working with computer code, be sure to describe the code (how it was constructed, intended input data, and expected output data). Clearly explain the results obtained, complete with thorough analysis and conclusions.
It is important to keep the following in mind when composing the homework assignments: In order to avoid plagiarism, be sure to rewrite any information obtained from external sources, and not to upload or scan images from textbooks or notes, but rather re-draw the illustrations in your own notes. Once ready for submission, the latest archived version of the homework assignment will be emailed to the TA's for evaluation and grading by the team coordinator. After the homework assignments have been evaluated, the top three HW reports will be selected by the TA's, given bonus points of 10%, 5% and 3%, as well as displayed by the TA's to benefit the remainder of the class. The Deadline for homework submission will be 5:00 pm EST, or 21:00 UTC of every Wednesday. Homework assignments will generally contain lecture notes though the preceding work week including the lecture notes from the Monday, Wednesday, and Friday classes.
|Exam Policies and Guidelines|
The following is the Exam schedule:
Chapters 1 & 4 - Methods for Solving Simple Trusses using the Matrix Method
Solving Trusses: Method of Broken Elements and Free Body Diagrams when solving Example Problem 1.1
|Simple Two Member Truss System||
The following example will outline some of the basic principles, procedures and notation that will be used to solve problems. This notation of solving problems will described in the "Recipe" and is one of the many forms of notation used in FEAD.
Figure 1: 2 Member Truss System
Figure 2: FBD of Truss System
f(e)i = ith internal force of element e
For this example:
Bar Element #2:
|One Fixed End|
Next step: Force-Displacement relationship (FD)
Figure 5: FD relation of 1-D spring element with one fixed end
Recalling that when given a spring constant, k [N/m] and a distance d, the Force, F [N] produced by a linear spring can be represented by the following equation:
|Two Free Ends|
Figure 6: FD relation of 1-D spring element with two free ends
The Stiffness Matrix
|Two Different, Yet Simple Cases|
Developing a "Recipe" to Simplify Problem Solving
The following sections will help in developing a recipe that will help us solve Truss problems with the use of FEA requirements and notation. Learning this scheme now will serve as an introduction to the remainder of the course.
|Step 1: Develop a Global Picture|
This Global Picture will give us a description of the problem at the structure level as well a schematic diagram, complete with the following:
|Step 2: Develop a Picture For Each Element|
It is important to draw element pictures for all elements in the system, so that one can use information already know in static mechanics to continue to breakdown the problem, and finally solve it. The element pictures should include:
Note: The Element picture may be place in the global coordinate system or in a local coordinate system
|Step 3: Define Global Force Displacement Relationships|
By defining global force displacement relationships, will allow for the following:
|4. Elimination of known Degree's of Freedom|
This can serve to simplify the problem so that unknown forces may be found, and solved for.
With the preceding information, we will use the recipe to solve for the required displacement degree of freedom vectors as well as the global forces.
|5. Computation of Element Forces|
The matrix K is non-singular, which allows inversion of the matrix With this known we can now say
|6. Computation of reaction forces|
We know have all the necessary tools to compute the unknown reaction forces.
Statically Determinate: Problem 1.2
The following is an example of a two member truss system which is known to be statically determinate. Given the specified information, and since it is statically determinate, this problem can be setup and solved using simple statics to determine any unknown forces, and moments. Solving this problem will also provide us with further exposure to FEAD notation in problem solving.
Figure 7: Two Member Truss System
- This problem can be solved using the knowledge of two forces members. It simplifies the unknowns so we have the same number of equations and unknowns. This means that we would not have to use the Finite Element Method (FEM). This problem can be solved by simply using a statics method learned previously. The system will generate forces that act along the members themselves which will reduce unknowns
Figure 8: Global Forces of Two Member Truss System
- The global forces are shown here in the global coordinate system. We see both the applied forces and the reactions forces. We see the additional unknowns (reaction forces) added to the system by removing the constraints of the ground connections.
Figure 9: First Element Forces
- The element is broken down and the element forces are displayed. With this we can now determine the magnitudes and direction of the combined forces. We see here that at the pin connection we display the reaction forces created by the separation of the two elements. With the two force member method we can solve the system
Figure 10: Second Element Forces
- The second element is broken down and the element forces are displayed. With this we can now determine the magnitudes and direction of the combined forces. We see here that at the pin connection we display the reaction forces created by the separation of the two elements. With the two force member method we can solve the system
Statically Indeterminate: Problem 1.3
For this problem we will use the "recipe" to explain why this truss system of members is considered statically indeterminate.
Figure 11: Statically Indeterminate Examples
- The two systems shown above are statically indeterminate using the standard static methods. They must be solved using Finite Element Method (FEM).
- The system to the left will generate 5 equations with 6 unknowns. That qualifies it as statically indeterminate by the standard statics method. We can solve for the reaction forces in the truss system. This forces use to use the "recipe" to solve the system.
- The system to the right will generate 3 equations with 6 unknowns. This once again forces us to use the "recipe" to solve for the system.
Figure 12: Global Force Breakdown of an Indeterminate System
Working with Element Equations, Solutions and Plane Trusses,
|1.1 Discretization and Element Equations|
The geometry of an element depends on the type of governing differential equation:
FEA has been popularized by the wide usage of FEA software.
|1.1.1 Plane Truss Element|
|1.2 Assembly of Elements Equation|
|1.4 Element Solutions and Model Validity|
Complete solutions to each element can be developed once the solution for all nodal degrees of freedom are available.
|1.4.1 Plane Truss Elemet|
The matlab primer helps introduce a beginner to Matlab. Matlab is a powerful programming language that is useful in math applications.
MATLAB can be accessed by typing in "matlab", or an icon maybe available on most computers.
MATLAB uses matrices as the basis of operation. All variables (elements) are represented as matrices. There are several methods used to enter matrices into MATLAB:
>>A=[1 2 3; 4 5 6; 7 8 9]
1 2 3
4 5 6
7 8 9
A=[1 2;3 4]+i*[5 6;7 8] or
A=[1+5i 2+6i; 3+7i 4+8i]
MATLAB automatically recognizes i or j as imaginary numbers unless they are defined differently
A new imaginary variable can be created if assigned as follows: ii=sqrt(-1)
The best way to enter large matrices is to create an extension file '.ext' in the editor. The data is opened in the command window by typing the name of the file followed by '.ext'. If a data file is named 'data' it can be opened by typing 'data.ext' into the command window.
Additional matrix generating functions are 'rand, magic, and hilb'.
Individual entries of a matrix can be referenced. For example, the matrix A shown above can have the value '4' from row 2 column 1 referenced by typing in A(2,1).
3. Matrix operations, array operations
Common math operations can be performed on matrices using the following syntax:
' conjugate transpose
\ left division
/ right division
The operations above can be performed on entry level values within a matrix by following the entered array with a period (.).For example:
>>[1 2 3 4].*[1 2 3 4]
1 4 9 16
4. Statements, expressions, and variables, saving a session
MATLAB reads expressions in the form of variables, functions, and operations. Typically a variable is assigned an expression in the format: 'variable = expression'. These statements are usually terminated with the carriage return key. Expressions can be carried over to another line using three consecutive periods in a row (...). Several expressions can be placed on one line using semicolons between expressions
All variables assigned in the MATLAB command window are lost when the program is closed. To prevent the loss of these variables type the command 'save' and the variables will be saved to a file named 'matlab.mat'. To reload these variables type 'load' the next time these variables are to be used.
5. Matrix building functions
6. For, while,- and relations
Example of a 'For' statement:
File:Forjpg.JPG Example of a 'While' statement:
Examples of a 'If' statements:
1. simple 'If' statement
2. Use of relation operators: <, >, <=, >=, ==, ~=
7. Scalar Functions
Some functions such as scalar functions apply element-wise when applied to a matrix. Some examples of these functions are: asin, acos, atan, exp, log, rem, abs, sqrt, etc.
8. Vector Functions
Other MATLAB functions can perform row or column calculations acting in a column-by-column fashion to produce a row vector of results. Row-by-row calculations can be obtained by using the transpose function.
Functions: (Use the help for more information)
A = [1 2 3; 4 5 6; 7 8 9] % 3x3 Matrix Test1 = max(A) % Find the Max number in each Row Test2 = max(A') % Find the Max number in each Column Test3 = max(max(A)) % Find the Max number in the Matrix
A = 1 2 3 4 5 6 7 8 9 Test1 = 7 8 9 Test2 = 3 6 9 Test3 = 9
9. Matrix Functions
MATLAB aslso has matrix functions with single or multiple outputs.
- eig - Eigenvalues and EigenVectors
- chol - Cholesky Factorization
- svd - Singular Value Decomposition
- inv - Inverse
- lu - LU Factoriztion
- qr - QA Factorization
- hess - Hessenberg Form
- schur - Schur Decomposition
- rref - Reduced Row Echelon Form
- expm - Matrix Exponential
- sqrtm - Matrix Square Root
- poly - Characteristic Polynomial
- det - Determinate
- size - Size
- norm - N-Norm
- cond - Condition Number in the 2-norm
- rank - Rank
A = [1 2 3; 4 5 6; 7 8 9] % 3x3 Matrix y = eig(A) % Produces a column vector of Matrix A's eigenvalues [U,D] = eig(A) % Matrix U whose column are eigenvalues and matrix D whoes diagonal are eigenvalues of A
A = 1 2 3 4 5 6 7 8 9 y = 16.1168 -1.1168 -0.0000 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
10. Command Line Editing and Recall
The command line in MATLAB can be editing using typical word processor methods. Type help cedit or cedit for more information.
You can recall previous command lines by using the up/down arrow keys. For example, you can compair sine waves with different frequencies in the command line.
m = 2; n=3; x=0:.01:2*pi; y=sin(m*x); z=cos(n*x); plot(x,y,x,z)
11. Submatrices and Colon Notation
Vectors and submatrices are used to calculate complex data. "Colon notation" is key to efficiently manipulate these objects. It is higly recommended that you are familiar with them
The expresstion "1:5" is actaully a row vector of "[1 2 3 4 5]". The numbers nor the increment do not have to be integers. For example, "0.2:0.2:1.2" gives "[0.2 0.4 0.6 0.8 1.0 1.2]" and "5:-1:1" gives "[5 4 3 2 1]".
x = [0.0:0.1:2.0]'; y = sin(x); [x y]
ans = 0 0 0.1000 0.0998 0.2000 0.1987 0.3000 0.2955 0.4000 0.3894 0.5000 0.4794 0.6000 0.5646 0.7000 0.6442 0.8000 0.7174 0.9000 0.7833 1.0000 0.8415 1.1000 0.8912 1.2000 0.9320 1.3000 0.9636 1.4000 0.9854 1.5000 0.9975 1.6000 0.9996 1.7000 0.9917 1.8000 0.9738 1.9000 0.9463 2.0000 0.9093
Since "sin" operates entry-wise, it produces a vector y from the vector x.
The colon notation can be used to access parts of the matrix. "A(1:4,3)" is a column vector consisting of the first four values of the third column.
A colon by itself means an entire row. "A(:,3) is the third column of A, and "A(1:4,:) is the first four rows.
Arbitrary intergral vectors can be used as subscripts. "A(:,[2 4])" is a column with the columns 2 and 4 of A.
Subscripting can be used on both side of the "=". "A(:,[2 3 4]) = B(:,1:3)" repaces columns 2,4,5 of A with the first three columns of B.
Matrices can also be multiplied using subscripting. "A(:,[2,4]) = A(:,[2,4])*[1 2;3 4]" multiplies columns 2 and 4 of A by the 2x2 matrix.
During these operations, The altered A matrix is permanently written.
x = [1 2 3] n = 3; x = x(3:-1:1) y = fliplr(x) y2 = flipud(x')
x = 1 2 3 x = 3 2 1 y = 1 2 3 y2 = 1 2 3
MATLAB can execute lines of code stored in files with the file type ".m". They can be editied using the MATLAB
Editor or any other local text editor. There are two types of M-files: script files and function
Script files are files with normal MATLAB codes. If the file has the filename, "test.m", and the MATLAB command
"test" in inputed, all the code in "test.m" is executed.
Function files extend the use of MATLAB by allowing you to create your own MATLAB functions. The variables in the
function file can either be declared local or global. Type help global for more information.
function a = randint(m,n,a,b) %RANDINT Randonly generated integral matrix % randint(m,n) returns an m-by-n such matrix with entries % between 0 and 9. % rand(m,n,a,b) return entries between integers a and b. if nargin < 3, a = 0; b = 9; end a = floor((b-a+1)*rand(m,n)) + a;
This should be placed in filename randint.m, which corresponds to the function name. MATLAB statements like
"z = randint(4,5)" can be used.
Functions can also have multiple outputs.
function [mean, stdev] = stat(x) %STAT Mean and standard deviation % For a vector x, stat(x) returns the mean of x; % [mean, stdev] = stat(x) both the mean and standard deviation. % For a matrix x, stat(x) acts columnwise. [m n] = size(x); if m== 1 m = n; % handle case of a row vector end mean = sum(x)/m; stdev = sqrt(sum(x.^2)/m - mean.^2);
This should be placed in filename stat.m. MATLAB statements like "[xm, xd] = stat(x)" can be used. Single
assignments can also be used. "xm = stat(x)" will assign the mean of x to xm.
The "%" symbol is used to add comments to your code. MATLAB will not run or recognise and input with the "%" in
front of it.
The following code is an example of an advanced function.
function [b, steps] = bisect(fun, x, tol) %BISECT Zero of a function of one variable via the bisection method. % bisect(fun,x) returns a zero of the function. fun is a string % containing the name of a real-valued MATLAB function of a % single real variablel; ordinaryily functions are defined in % M-files. x is a starting guess. The value returned is near % a point where fun changes sign. For example, % bisect('sin',3) is pi. Note the quotes around sin. % % An optional third input arguments sets a tolerance for the % relative accuracy of the results. The defauly is eps. % An optional second output argument gives a matrix containing a % trace of the stepsl the rows are of form [c f(c)]. % Initialization if nargin < 3, tol = eps; end trace = (nargout == 2); if x ~=0, dx = x/20; else, dx = 1/20; end a = x - dx; fa = feval(fun,a); b = x + dx; fb = feval(fun,b); % Find change of sign while (fa > 0) == (fb > 0) dx = 2.0dx; a = x - dx; fa = feval(fun,a); if (fa > 0) ~= (fb > 0), break, end b = x + dx; fb = feval(fun,b); end if trace, steps = [a fa; b fb]; end % Main Loop while abs(b - a) > 2.0*tol*max(abs(b),1.0) c = a + 0.5*(b - a); fc = feval(fun,c); if trace, steps = [steps; [c fc]]; end if (fb > 0) == (fc > 0) b = c; fb = fc; else a = c; fa = fc; end end
Some MATLAB functions are built in, while other are in M-files.
13. Text Strings, Error Messages, Input
Text strings can be entered in MATLAB. They can either be assigned to a varibale, displayed as a message or error, or used to promt the user to input a value. The code shows them respectively.
s = 'This is a test of the Emergency Broadcast System and so forth...' disp('I command you to display this message!!!') error('Gomen nasai! Sorry! You got pwned! Check your MATLAB code!') iter = input('Enter the value for variable x: ')
14. Managing M-files
Any system command beginning with ! is executed without leaving MATLAB. The !-feature can be used to create or edit an M-file with the local editor then return to MATLAB without deactivating it (which would delete all variables). For example, the code !-ed rotate.m with allow you to edit rotate.m using the local editor, then return back to MATLAB.
On systems allowing multiple processes, such as Unix or MS Windows, it may be easiest to keep both MATLAB and the local editor active while working.
Debugging tools are available. The command help dbtype provides more information.
Some system commands do not require the use of an !:
- pwd - returns the name of the present working directory
- cd - changes the working directory
- dir or ls - lists the contents of the working directory
- what - lists only M-files from the directory
- delete - deletes the specified diskfile
- type - prints the specified M-file to the screen
M-files must be stored in a directory that is directly accessible by MATLAB. Most mainframe or workstation network installations place personal M-files in a subdirectory of the home directory named matlab. The command path displays a current list of directories obtained by MATLAB's search path. See help path for more details.
15. Comparing efficiency of algorithms: flops, tic and toc
The command flops keeps a running total of the number of flops performed. The command flops(0) resets this count to zero. Thus, to count the number of flops in an algorithm, enter flops(0) immediately before and flops immediately after the algorithm is performed. NOTE: the command flops is a floating point operation count that is now obsolete. Earlier version of MATLAB included it, but the incorporation of the function LAPACK in MATLAB 6, it no longer had a practical use.
Stopwatch timers tic and toc calculate the elapsed time from an execution. For example, if A is a matrix [n x n] and b is a vector [n x 1], the following code will display the time for solving the linear system x=A/b:
tic, x=A/b; toc
Another useful feature is comparing the execution time of two different statements solving the same equation. For example, x=A/b vs. x=inv(A)*b.
On timesharing machines, elapsed time may not be extremely accurate since other running processes may slow down execution time.
16. Output Format
All MATLAB computations are performed in double precision. However, the following commands control the output format:
- format short - fixed with 4 decimal places (default)
- format long - fixed with 14 decimal places
- format short e - scientific notation with 4 decimal places
- format long e - scientific notation with 4 decimal places
- format rat - approximation by ratio of small integers
- format hex - hexadecimal format
- format bank - fixed dollars and cents
- format + - +,-,blank
- format compact - supresses most blank lines; allows more information to fit on the page
- format loose - returns to non-compact format
The last two are independent of the other format commands. The new format will then ensue until changed.
The command diary filename sends what follows on the screen (excluding graphics) to the specified diskfile. If no name is given, it is written to a default file named "diary". The command diary off stops the recording; disk on turns it back on. When finished writing to the file, it can be printed from the system.
The "!-feature" also allows the editing and printing of code without leaving MATLAB (refer to section 14).
Several types of graphics can be produced by MATLAB, including:
- planar plots (primary command: plot)
- 3-D plots (primary command: plot3)
- 3-D mesh surface plots (primary command: mesh)
- 3-D faced surface plots (primary command: surf)
It may be useful to keep the graphics window- "Figure"- open and moved to the side while keeping the command window active. It is possible to have multiple graphics windows open at a time; one will be the "current" figure (where subsequent commands are plotted). To change which figure is "current", one may type figure(X) [X being any number]. This will open the Xth, and now current, figure. he command gcf returns the number of the current figure.
The command print will print a high-resolution copy of the current figure to the default printer. The M-file printopt specifies the default setting used by the print command, and can be edited to change the printing defaults.
The command print filename saves the current figure to filename in the default file format. If filename has no extension, a suitable extension will be added (ie: .ps, .eps, or .jet).
The following information, or the command demo, may be used to preview the graphics options.
The command plot forms linear x-y plots. Assuming x and y are vectors of the same length, plot(x,y) graphs a 2-dimensional x-y plot of x vs. y in a new window. (See Code 1 and Code 2).
The command fplot can be used to plot a defined function, including from an M-file. (See Code 3).
Graphics can be formatted with the following commands:
- title - graph title
- xlabel - x-axis label
- ylabel - y-axis label
- gtext - place text on graph using mouse
- text - position text on graph at specified coordinates
- grid - places grid lines on the plot
The axes are auto-scaled, but can be overwritten using the command axis, which has the following uses: (should be given AFTER the plot command)
- axis([xmin,xmax,ymin,ymmax]) - scales axes to these limits
- axis(axis) - freezes scaling of axes for following graphs
- axis auto - returns to default axis scaling
- v = axis - returns vector v showing current scaling
- axis square - sets same scale on both axes
- axis equal - sets same scale and tic marks on both axes
- axis off - turns off axis scaling an tic marks
- axis on - turns on axis scaling an tic marks
More than one plot can be represented on a single graph. (See Code 5a and 5b). The command hold accomplishes the same thing by freezing the current plot on the graph and layer subsequent plots on top of it. Entering hold off will end this command.
The default linetypes, marktypes, and colors can be reformatted. (See Code 6 and Code 7). Use the following guidelines:
- Linetypes: solid (-), dashed (--), dotted (:), dashdot (-.)
- Marktypes: point (.), plus (+), star ("*"), circle (o), x-mark (x)
- Colors: yellow (y), magenta (m), cyan (c), red (r), green (g), blue (b), white (w), black (k)
The command subplot breaks the screen up in order to place several small plots in one figure. The command help subplot can be used for further instruction.
Other 2-D plotting functions (that can be explored using help):
Code 1: x = -4:.01:4; y = sin(x); plot(x,y)
–Plots the sine function over the interval -4 to 4; x is a division of the domain with meshsize 0.01; y is a vector of the values of sine at the nodes of x
Code 2: x = -1.5:.01:1.5; y = exp(-x.^2); plot(x,y)
–Plots y=e-x2 from -1.5 to 1.5
Code 4: t = 0:.001:2*pi; x = cos(3*t); y = sin(2*t); plot(x,y)
Code 5a: x = 0:.01:2*pi; y1 = sin(x); y2 = sin(2*x); y3 = sin(4*x); plot(x,y1,x,y2,x,y3)
Code 5b (uses matrix Y; produces same display): x = 0:.01:2*pi; Y=[sin(x)', sin(2*x)', sin(4*x)']; plot(x,Y)
Code 6: x = 0:.01:2*pi; y1 = sin(x); y2 = sin(2*x); y3 = sin(4*x); plot(x,y1,'--',x,y2,':',x,y3,'+')
Displays same plot as Code 5 with different line formats.
Code 7: plot(x,y,'r--')
Displays a red dashed line.
3D Line Plots
Similar to plot, the command plot3 displays curves in 3 dimensions. Assuming x, y, and z are vectors of the same length, plot3(x,y,z) graphs a perspective plot of the linear curve in 3-D space of the respective elements of x, y,, and z, which are often defined parametrically. (See Code 1).
Using the same commands as for planar plots, a title and axis labels can be added (including zlabel). The axis command features also work as explained earlier, except now the axis scaling limits require a 6-vector.
Code 1: t = .01:.01:20*pi; x = cos(t); y = sin(t); z = t.^3; plot3(x,y,z)
Displays a helix that is compressed near the x-y plane.
3D Mesh and Surface Plots
The command mesh produces 3-dimensional wire mesh plots. (See Code 1 and 2).
Similarly, the command surf produces 3-dimensional faceted surface plots. (See Code 3).
Below are more examples of mesh and surface plots. (See Code 4 and Code 5).
Formatting for 3-D surface and mesh plots is similar to other plots, including commands to reformat the title, axes and their labels as well as hold.
1. shading: Shades the surfaces of plots different colors. These commands should be entered AFTER the surf command. The three settings for shading are:
- shading faceted (default)
- shading interp (interpolated- removes superimposed meshlines on surf plots)
- shading flat (flat- removes superimposed meshlines on surf plots)
2. colormap: Controls a surface's color profile. Predefined colormaps include: hsv (default), hot, cool, jet, pink, copper, flag, gray, and bone. For example, typing colormap(cool) will set a certain color profile for the current figure. (See Code 6).
3. view: Specifies the viewpoint from which is object is to be viewed in cartesian or spherical coordinates. (See help view for more details).
4. peaks: Produces plot good for experimenting with shading, colormap, and view. (See Code 7, Code 8, and Code 9).
Parametrically defined surfaces can also be used in producing plots. (See Code 10).
More 3-D plotting functions to explore via help:
Code 1: mesh(z)
Displays a 3-D perspective plot of the elements of pre-defined matrix "z"
Code 2: mesh(eye(10))
Code 3: surf(eye(10))
Code 4: xx = -2:.2:2; yy = xx; [x,y] = meshgrid(xx,yy); z = exp(-x.^2-y.^2); mesh(z)
Displays the MESH plot of z=e-x2-y2 over the square [-2,2]X[-2,2]
Code 5: xx = -2:.2:2; yy = xx; [x,y] = meshgrid(xx,yy); z = exp(-x.^2-y.^2); surf(z)
Displays the SURFACE plot of z=e-x2-y2 over the square [-2,2]X[-2,2]
Initial Code 7: peaks
z = 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ... - 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ... - 1/3*exp(-(x+1).^2 - y.^2)
Code 7a: shading flat
Code 7b: colormap(flag)
Code 7c: view
The system Handle Graphics allows for the production of sophisticated plots; it provides functions to control all aspects of the graphics environment. For example:
Please refer to the MATLAB User's Guide for more information on Handle Graphics.
19. Sparse Matrix Computations
MATLAB has two matrix storage modes: full (default) and sparse. The functions full and sparse convert between the two modes. Since MATLAB assumes matrices are dense with non-zero entries, computation time can be reduced and memory use can be minimized by storing only the non-zero entries of a sparse matrix. For any matrix A, nnz(A) returns the number of nonzero elements in A.
Sparse matrices are stored as linear arrays of their nonzero entries along with their row and column indices. See the following example:
Example Code:Creates a full tridiagonal matrix, F and converts it to sparse mode.
F = floor(10*rand6(6)); F = triu(tril(F,1),-1); S = sparse(F)
Related Code: Converts S to full storage mode and displays the storage mode of matrix A.
F = full(S); issparse(A)
The command spdiags creates a sparse matrix by specifying the diagonals. See the following example and help spdiags for more information.
m = 6; n = 6; e = ones(n,1); d = -2*e; T = spdiags([e,d,e],[-1,0,1],m,n)
- speye - sparse analog for full matrix of eye
- sparse - sparse analog for full matrix of zeroes
- spones - sparse analog for full matrix of ones; takes matrix argument and replaces only nonzero entries with ones
- sprandn - sparse analog for full matrix of randn; takes matrix argument and replaces only nonzero entries with normally distributed random numbers
- sparse(m,n) - sparse zero matrix
The command sparse can also create a sparse matrix via listing its nonzero entries. See following example:
Example Code 1: Vector s lists nonzero entries of S, integral vectors i and j list their row and column indices respectively, then creates sparse matrix S with dimensions m x n).
i = [1 2 3 4 4 4]; j = [1 2 3 1 2 3]; s = [5 6 7 8 9 10]; S= sparse(i,j,s,4,3), full(S); sparse(i,j,s,m,n)
Example Code 2:
<\source> n = 6; e = floor(10*randn(n-1,1)); E=sparse(2:n,1:n-1,e,n,n)
Operations and functions can be performed on matrices in both full and sparse modes. Resulting storage mode guidelines are as follows:
- Opeations on FULL matrices give FULL results
- FULL: S+F, S*F, S\F, F\S
- SPARSE: S+S, S*S, S.*S, S.*F, S^n, S.^n, S\S; inv(S), chol(S), lu(S), diag(S), max(S), sum(S)
- If S is SPARSE, eig(S) is full if S is symmetric but undefined if S is unsymmetric
- svd - a FULL argument
- Matrices built from blocks (ie: [A,B;C,D] is SPARSE if any block is sparse
Example: The following code compares the efficiency of the two storage modes for solving a tridiagonal system of equations for n=20,50,500,1000:
n=20; e=ones(n,1); d=-2*e; T=spdiags([e,d,e],[-1,0,1],n,n); A=full(T); b=ones(n,1); s=sparse(b); tic,T\s; sparsetime=toc, tic,A\b; fulltime=toc
MATLAB has many features that have not been included in this introduction. It contains many functions and operators that can be referenced via the on-line help facility or the Reference Guide.
There also exists "toolboxes" of functions for specific purposes, including:
- Signal processing
- Control systems
- System identification
- μ-analysis and synthesis
- State-space identification
- Neural networks
- Image processing
- Symbolic math (Maple kernel)
These toolboxes can be further explored using help. }
The following Team Aero members contributed to this report.
Rodney Dagulo --Eml4500.f08.wiki.dagulo.r 19:18, 18 September 2008 (UTC)
Renee Hood -- Eml4500.f08.wiki.hood
Cortland Glowacki -- Eml4500.f08.wiki.cort 12:01, 19 September 2008 (UTC)
Ricardo Lopez -- Eml4500.f08.wiki.Lopez 12:12, 19 September 2008 (UTC)
Thomas Kehoe -- Eml4500.f08.wiki.Kehoe 12:14, 19 Septempber 2008 (UTC)