# User:Eml4500.f08.wiki.hood

See my comments below. Eml4500.f08 11:03, 21 September 2008 (UTC)

# 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.

## Course Information

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.

# Chapters 1 & 4 - Methods for Solving Simple Trusses using the Matrix Method

## 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.

## 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.

Error 2: No, please review the lecture presentation on this topic: Using statics, there are only 3 unknowns (due to 2-force bodies) with only 2 usable equations (the moment equation is useless). Also review the lecture presentation on "Euler cut principle". Eml4500.f08 10:59, 21 September 2008 (UTC)

Figure 12: Global Force Breakdown of an Indeterminate System

# Matlab Primer

## Introduction

The matlab primer helps introduce a beginner to Matlab. Matlab is a powerful programming language that is useful in math applications.

## 1.Accessing MATLAB

MATLAB can be accessed by typing in "matlab", or an icon maybe available on most computers.

## 2.Entering Matrices

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:

Example:

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

A =
1 2 3
4 5 6
7 8 9

Complex Matrices
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:

- subtraction

• multiplication

^ power
' conjugate transpose
\ left division
/ right division

Array operations
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]
ans
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

There are many types of matrix building functions. Some examples of the uses of the zeros, diag, and eye functions are shown below.

File:Section5part1.JPG
File:Section5part2.gif

## 6. For, while,- and relations

Example of a 'For' statement:
File:Forjpg.JPG Example of a 'While' statement:
File:Whilejpg.JPG
Examples of a 'If' statements:
1. simple 'If' statement
File:SimpleIf.JPG
2. Use of relation operators: <, >, <=, >=, ==, ~=
File:Relations1.JPG
File:Relations2.JPG

## 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.

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

Example:
Code:

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


Output:

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.

Functions:

• 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

Example:
Code:

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


Output:

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.

Example:
Code:

m = 2; n=3; x=0:.01:2*pi; y=sin(m*x); z=cos(n*x); plot(x,y,x,z)


Output:

## 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]".
Example:

Code:

x = [0.0:0.1:2.0]';
y = sin(x);
[x y]


Output:

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.

Example:

Code:

x = [1 2 3]
n = 3;
x = x(3:-1:1)
y = fliplr(x)
y2 = flipud(x')


Output:

x =

1     2     3

x =

3     2     1

y =

1     2     3

y2 =

1
2
3


## 12. M-files

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

files

Script Files
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
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. Example:

Code:

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.
Code:

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.

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. Code:

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.

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:

Code:

tic, x=A/b; toc


Display:

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.

## 17. Hardcopy

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).

## 18. Graphics

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.

Graphics Hardcopy

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.

Planar Plots

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):

• polar
• bar
• hist
• quiver
• compass
• feather
• rose
• stairs
• fill

Examples:

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
Display 1:
File:Planarplot1.jpg

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
Display 2:
File:Planarplot2.jpg

Code 3: sphere
-Plots a parametrically defined sphere
Display 3:

Code 4: t = 0:.001:2*pi; x = cos(3*t); y = sin(2*t); plot(x,y)
Display 4:
File:Planarplot4.jpg

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)
Display 5:
File:Planarplot5a.jpg

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.
Display 6:

File:Planarplot6.jpg

Code 7: plot(x,y,'r--')
Displays a red dashed line.
Display 7:

File:Planarplot7.jpg

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.
Display 1:
File:3dlineplot1.jpg

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.

More commands:

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 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:

• meshz
• surfc
• surf1
• contour
• pcolor

Code 1: mesh(z)
Displays a 3-D perspective plot of the elements of pre-defined matrix "z"
Display 1:
File:3dmeshsurface1a.jpg

Code 2: mesh(eye(10))
Display 2:
File:3dmeshsurface1.jpg

Code 3: surf(eye(10))
Display 3:
File:3dmeshsurface2.jpg

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]
Display 4:
File:3dmeshsurface3.jpg

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]
Display 5:
File:3dmeshsurface4.jpg

Code 6: colormap(cool)
Display 6:

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)

Display 7a:

Code 7b: colormap(flag)
Display 7b:

Code 7c: view
Display 7c:
File:7c.jpg

Handle Graphics

The system Handle Graphics allows for the production of sophisticated plots; it provides functions to control all aspects of the graphics environment. For example:

• set(1)
• gca,set(ans)

## 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)


Display:

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.

Example Code:

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


More Commands:

• 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)

More examples:

• 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:
Code:

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


Display:

## 20. Reference

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
• Robust-control
• System identification
• Optimization
• Splines
• Chemometrics
• μ-analysis and synthesis
• State-space identification
• Neural networks
• Image processing
• Symbolic math (Maple kernel)
• Statistics

These toolboxes can be further explored using help. }

# Contributing Members

The following Team Aero members contributed to this report.

Gonzalo Barcia --Eas4200c.f08.aero.barcia and Eml4500.f08.wiki.barcia 06:47, 18 September 2008 (UTC)

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)