Programing The Finite Element Method With Matlab: Jack Chessa
Programing The Finite Element Method With Matlab: Jack Chessa
Matlab
Jack Chessa
1 Introduction
The goal of this document is to give a very brief overview and direction in
the writing of nite element code using Matlab. It is assumed that the
reader has a basic familiarity with the theory of the nite element method,
and our attention will be mostly on the implementation. An example nite
element code for analyzing static linear elastic problems written in
Matlab is presented to illustrate how to program the nite element
method. The example program and supporting les are available at
http://www.tam.northwestern.edu/jfc795/Matlab/
1.1 Notation
For clarity we adopt the following notation in this paper; the bold italics font v
denotes a vector quantity of dimension equal to the spacial dimension of the
problem i.e. the displacement or velocity at a point, the bold non-italicized font d
denotes a vector or matrix which is of dimension of the number of unknowns in
the discrete system i.e. a system matrix like the sti ness matrix, an uppercase
subscript denotes a node number whereas a lowercase subscript in general
denotes a vector component along a Cartesian unit vector. So, if d is the
system vector of nodal unknowns, uI is a displacement vector of node I and uIi
is the component of the displacement at node I in the i direction, or u I ei. Often
Matlab syntax will be intermixed with mathematical notation
Graduate Research Assistant, Northwestern University ([email protected])
1
which hopefully adds clarity to the explanation. The typewriter font, font,
is used to indicate that Matlab syntax is being employed.
for i=1:size(A,2)
A(n,i)=0;
end
for i=1:size(A,1)
A(i,n)=0;
end
2
A(n,n)=1;
A(:,n)=0;
A(:,n)=0;
A(n,n)=0;
1. Preprocessing section
2. Processing section
3. Post-processing section
In the preprocessing section the data and structures that de ne the particular
problem statement are de ned. These include the nite element discretiza-tion,
material properties, solution parameters etc. . The processing section is where
the nite element objects i.e. sti ness matrices, force vectors etc. are computed,
boundary conditions are enforced and the system is solved. The post-
processing section is where the results from the processing section are
analyzed. Here stresses may be calculated and data might be visualized. In this
document we will be primarily concerned with the processing section. Many pre
and post-processing operations are already programmed in Matlab and are
included in the online reference; if interested one can either look di-rectly at the
Matlab script les or type help 'function name' at the Matlab command line to get
further information on how to use these functions.
3
4 Finite Element Data Structures in Matlab
Here we discuss the data structures used in the nite element method
and speci cally those that are implemented in the example code. These
are some-what arbitrary in that one can imagine numerous ways to store
the data for a nite element program, but we attempt to use structures
that are the most exible and conducive to Matlab. The design of these
data structures may be depend on the programming language used, but
usually are not signi cantly di erent than those outlined here.
2 0:0 0:0 3
nodes = 6 6
2:0
2:0
0:0
3:0
7 :
7
(1)
6 6
0:00:0
3:06:0
77
6 6
2:0 6:0 77
4 5
4.2 Element Connectivity Matrix
The element de nitions are stored in the element connectivity matrix. This is
a matrix of node numbers where each row of the matrix contains the con-
nectivity of an element. So if we consider the connectivity matrix elements
that describes a mesh of 4-node quadrilaterals the 36th element is de ned
by the connectivity vector elements(36,:) which for example may be [ 36 42
13 14] or that the elements connects nodes 36 ! 42 ! 13 ! 14. So for
4
the simple mesh in Figure 1 the element connectivity matrix is
1 2 3
elements = 2 62 54 43 73 :
6 (2)
4 5 2
6 7
4 5
Note that the elements connectivities are all ordered in a counter-clockwise
fashion; if this is not done so some Jacobian's will be negative and thus can
cause the sti nesses matrix to be singular (and obviously wrong!!!).
2 4
right Edge = 4 6: (3)
Note that the numbers in the boundary connectivity matrix refer to the
same node coordinate matrix as do the numbers in the connectivity
matrix of the interior elements. If we wish to apply an essential boundary
conditions on this edge we need a list of the node numbers on the edge.
This can be easily done in Matlab with the unique function.
nodesOnBoundary = unique(rightEdge);
This will set the vector nodesOnBoundary equal to [2 4 6]. If we wish to
from a force vector from a natural boundary condition on this edge we
simply loop over the elements and integrate the force on the edge just as
we would integrate any nite element operators on the domain interior i.e.
the sti ness matrix K.
5
4.4 Dof Mapping
Ultimately for all nite element programs we solve a linear algebraic
system of the form
Kd = f (4)
for the vector d. The vector d contains the nodal unknowns for that de ne
the nite element approximation
nn
X
uh(x) = NI (x)dI (5)
I=1
where NI (x) are the nite element shape functions, dI are the nodal un-
knowns for the node I which may be scalar or vector quantities (if u h(x) is
a scalar or vector) and nn is the number of nodes in the discretization.
For scalar elds the location of the nodal unknowns in d is most obviously
as follows
dI = d(I); (6)
but for vector elds the location of the nodal unknown d Ii, where I refers to
the node number and i refers to the component of the vector nodal
unknown dI , there is some ambiguity. We need to de ne a mapping from
the node number and vector component to the index of the nodal
unknown vector d. This mapping can be written as
f : fI; ig ! n (7)
where f is the mapping, I is the node number, i is the component and n is
the index in d. So the location of unknown uIi in d is as follows
u =d :
Ii f(I;i) (8)
There are two common mappings used. The rst is to alternate
between each spacial component in the nodal unknown vector d. With
this arrange-ment the nodal unknown vector d is of the form
2 3
u
1x
u 1y
6 6
... u2x
7
7
6 7
d= 6 u2y 7 (9)
6 7
6 .. 7
6 . 7
6 7
6 7
6 7
6 7
6
unn x 7
6 7
6
45
unn y 7
.
..
6
where nn is again the number of nodes in the discretization. This
mapping is
n = sdim(I 1) + i: (10)
With this mapping the i component of the displacement at node I is
located as follows in d
dIi = d( sdim*(I-1) + i ): (11)
The other option is to group all the like components of the nodal un-
knowns in a contiguous portion of d or as follows
2 3
u1x
6
6
u2x7 7
...
6 7
6 7
u
d= nx (12)
6 u1y 7
6 u2y 7
6 7
6 .. 7
6 . 7
4 5
The mapping in this case is
n = (i 1)nn + I (13)
So for this structure the i component of the displacement at node I is
located at in d
dIi = d( (i-1)*nn + I ) (14)
For reasons that will be appreciated when we discuss the scattering of
element operators into system operators we will adopt the latter dof
mapping. It is important to be comfortable with these mappings since it is
an operation that is performed regularly in any nite element code. Of
course which ever mapping is chosen the sti ness matrix and force
vectors should have the same structure.
The global operators are evaluated by looping over the elements in the
dis-cretization, integrating the operator over the element and then to
scatter the local element operator into the global operator. This
procedure is written mathematically with the Assembly operator A
Z
K = Ae BeT C Be d (17)
e
5.1 Quadrature
The integration of an element operator is performed with an appropriate
quadrature rule which depends on the element and the function being
inte-grated. In general a quadrature rule is as follows
Z =1
X
f( )d = f( q)W q (18)
= 1 q
[quadWeights,quadPoints] = quadrature(integrationOrder,
elementType,dimensionOfQuadrature);
[qPt,qWt]=quadrature(3,'TRIANGULAR',2);
for q=1:length(qWt)
xi = qPt(q); % quadrature point
% get the global coordinte x at the quadrature point xi
% and the Jacobian at the quadrature point, jac
...
f_int = f_int + x^3 * jac*qWt(q);
end
8
5.2 Operator "Scattering"
Once the element operator is computed it needs to be scattered into the
global operator. An illustration of the scattering of an element force
vector into a global force vector is shown in Figure 2. The scattering is
dependent on the element connectivity and the dof mapping chosen. The
following code performs the scatter indicated in Figure 2
but uses a nested for loop (bad bad bad). This is an even more egregious act
considering the fact that it occurs within an element loop so this can really slow
down the execution time of the program (by orders of magnitude in many
cases). And it gets even worse when scattering a matrix operator (sti ness
matrix) since we will have four nested for loops. Fortunately, Matlab allows for
an easy solution; the following code performs exactly the same scattering as is
done in the above code but with out any for loops, so the execution time is
much improved (not to mention that it is much more concise).
To scatter an element sti ness matrix into a global sti ness matrix the fol-
lowing line does the trick
This terse array indexing of Matlab is a bit confusing at rst but if one
spends a bit of time getting used to it, it will become quite natural and
useful.
9
this involves modifying the system
Kd = f (19)
so that the essential boundary condition
dn = d n (20)
is satis ed while retaining the original nite element equations on the un-
constrained dofs. In (20) the subscript n refers to the index of the vector
d not to a node number. An easy way to enforce (20) would be to modify
nth row of the K matrix so that
fn = dn: (22)
th
This reduces the n equation of (19) to (20). Unfortunately, this destroys
the symmetry of K which is a very important property for many e cient
linear solvers. By modifying the nth column of K as follows
fm = Kmndn: (24)
th
If we write the modi ed k equation in (19)
K d +K d +: : : K d +
k1 1 k2 2 k(n 1) n 1
K d +: : :+K d = f K d
k(n+1) n+1 kN N k kn n (25)
it can be seen that we have the same linear equations as in (19), but just
with the internal force from the constrained dof. This procedure in Matlab
i s as follows
f = f - K(:,fixedDofs)*fixedDofValues;
K(:,fixedDofs) = 0;
K(fixedDofs,:) = 0;
K(fixedDofs,fixedDofs) = bcwt*speye(length(fixedDofs));
f(fixedDofs) = bcwt*fixedDofValues;
where fixedDofs is a vector of the indicies in d that are xed,
fixedDofValues is a vector of the values that fixedDofs are assigned to and
bcwt is a weighing factor to retain the conditioning of the sti ness matrix
(typically bcwt = trace(K)=N).
10
6 Where To Go Next
Hopefully this extremely brief overview of programming simple nite element
methods with Matlab has helped bridge the gap between reading the theory
of the nite element method and sitting down and writing ones own nite
element code. The examples in the Appendix should be looked at and run,
but also I would suggest trying to write a simple 1D or 2D nite element code
from scratch to really solidify the method in ones head. The examples can
then be used as a reference to diminish the struggle. Good Luck!
11
A Installation of Example Matlab Program
All the functions needed to run the example programs as well as the examples
themselves can be found at
http://www.tam.northwestern.edu/jfc795/Matlab/
I believe that the following les are required, but if one gets a run error
about function not found chances are that I forgot to list it here but it is in
one of the Matlab directories at the above web site.
There are many additional les that one might nd useful and an interested
individual can explore these on there own. These es should be copied
either the directory which contains the example script le or into a
directory that is in the Matlab search path.
12
B Example: Beam Bending Problem
The rst example program solves the static bending of a linear elastic beam.
The con guration of the problem is shown in Figure 3 and the program can
be found at
http://www.tam.northwestern.edu/jfc795/Matlab/
Examples/Static/beam.m
The exact solution for this problem is as follows
= P (L x)y
11
I
22 = 0
12 P
= 2 I (c2 y2)
u1 P y
= 6 EI 3 L2 (L x)2 + (2 + )(y2 c2))
u2 Py
3 3 2 2 2
= 6EI 3 (L x) L (4 + 5 )c + 3L x + 3 (L x)y
This problem can be run with three element types; three node triangle
element, a four node quadrilateral element and a nine node quadrilateral ele-
ment. Also, one can choose between plane strain or plane stress assumption.
% beam.m
%
% Solves a linear elastic 2D beam problem ( plane stress or strain )
% with several element types.
%
% ^y
% |
% ---------------------------------------------
% | |
% | |
% --------- >x | 2c
% | |
% | L |
% ---------------------------------------------
%
% with the boundary following conditions:
%
% u_x = 0 at (0,0), (0,-c) and (0,c)
% u_y = 0 at (0,0)
%
% t_x = y along the edge x=0
% t_y = P*(x^2-c^2) along the edge x=L
%
% ******************************************************************************
%
% This file and the supporting matlab files can be found at
% http://www.tam.northwestern.edu/jfc795/Matlab
%
% by Jack Chessa
% Northwestern University
13
%
% ******************************************************************************
clear
colordef black
state = 0;
% ******************************************************************************
% *** INPUT ***
% ******************************************************************************
tic;
disp('************************************************')
disp('*** STARTING RUN ***')
disp('************************************************')
disp([num2str(toc),' START'])
% MATERIAL PROPERTIES
E0 = 10e7; % Young's modulus
nu0 = 0.30; % Poisson's ratio
% BEAM PROPERTIES
L = 16; % length of the beam
c = 2;% the distance of the outer fiber of the beam from the mid-line
% MESH PROPERTIES
elemType = 'Q9'; % the element type used in the FEM simulation; 'T3' is for a
% three node constant strain triangular element, 'Q4' is for
% a four node quadrilateral element, and 'Q9' is for a nine
% node quadrilateral element.
% STRESS ASSUMPTION
stressState='PLANE_STRESS'; % set to either 'PLANE_STRAIN' or "PLANE_STRESS'
% nuff said.
% ******************************************************************************
% *** PRE-PROCESSING ***
% ******************************************************************************
I0=2*c^3/3; % the second polar moment of inertia of the beam cross-section.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
14
% Here we gnerate the finte element mesh (using the approriate elements).
% I won't go into too much detail about how to use these functions. If
% one is interested one can type - help 'function name' at the matlab comand
% line to find out more about it.
%
% The folowing data structures are used to describe the finite element
% discretization:
%
% node - is a matrix of the node coordinates, i.e. node(I,j) -> x_Ij
% element - is a matrix of element connectivities, i.e. the connectivity
% of element e is given by > element(e,:) -> [n1 n2 n3 ...];
%
% To apply boundary conditions a description of the boundaries is needed. To
% accomplish this we use a separate finite element discretization for each
% boundary. For a 2D problem the boundary discretization is a set of 1D elements.
%
% rightEdge - a element connectivity matrix for the right edge
% leftEdge - I'll give you three guesses
%
% These connectivity matricies refer to the node numbers defined in the
% coordinate matrix node.
inc_u=1;
inc_v=nnx;
node_pattern=[ 1 2 nnx+2 nnx+1 ];
element=make_elem(node_pattern,numx,numy,inc_u,inc_v);
inc_u=2;
inc_v=2*nnx;
node_pattern=[ 1 3 2*nnx+3 2*nnx+1 2 nnx+3 2*nnx+2 nnx+1 nnx+2 ];
element=make_elem(node_pattern,numx,numy,inc_u,inc_v);
node_pattern1=[ 1 2 nnx+1 ];
node_pattern2=[ 2 nnx+2 nnx+1 ];
inc_u=1;
inc_v=nnx;
element=[make_elem(node_pattern1,numx,numy,inc_u,inc_v);
make_elem(node_pattern2,numx,numy,inc_u,inc_v) ];
end
% DEFINE BOUNDARIES
15
% Here we define the boundary discretizations.
uln=nnx*(nny-1)+1;% upper left node number
urn=nnx*nny; % upper right node number
lrn=nnx; % lower right node number
lln=1; % lower left node number
cln=nnx*(nny-1)/2+1; % node number at (0,0)
switch elemType
case 'Q9'
rightEdge=[ lrn:2*nnx:(uln-1); (lrn+2*nnx):2*nnx:urn; (lrn+nnx):2*nnx:urn ]'; leftEdge =[ uln:-
2*nnx:(lrn+1); (uln-2*nnx):-2*nnx:1; (uln-nnx):-2*nnx:1 ]'; edgeElemType='L3';
end
% PLOT MESH
if ( plotMesh ) % if plotMesh==1 we will plot the mesh
clf
plot_mesh(node,element,elemType,'g.-');
hold on
plot_mesh(node,rightEdge,edgeElemType,'bo-');
plot_mesh(node,leftEdge,edgeElemType,'bo-');
plot(node(fixedNodeX,1),node(fixedNodeX,2),'r>');
plot(node(fixedNodeY,1),node(fixedNodeY,2),'r^');
axis off
axis([0 L -c c])
disp('(paused)')
pause
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
16
f=zeros(2*numnode,1); % external load vector
K=sparse(2*numnode,2*numnode); % stiffness matrix
% a vector of indicies that quickly address the x and y portions of the data
% strtuctures so U(xs) returns U_x the nodal x-displacements
xs=1:numnode; % x portion of u and v vectors
ys=(numnode+1):2*numnode; % y portion of u and v vectors
% ******************************************************************************
% *** PROCESSING ***
% ******************************************************************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% RIGHT EDGE
for e=1:size(rightEdge,1) % loop over the elements in the right edge
% LEFT EDGE
for e=1:size(leftEdge,1) % loop over the elements in the left edge
sctr=rightEdge(e,:);
sctrx=sctr;
sctry=sctrx+numnode;
yPt=N'*node(sctr,2);
fyPt=-P*(c^2-yPt^2)/(2*I0); % y traction at quadrature point
fxPt=P*L*yPt/I0; % x traction at quadrature point
17
f(sctry)=f(sctry)+N*fyPt*detJ0*wt;
f(sctrx)=f(sctrx)+N*fxPt*detJ0*wt;
% set the force at the nodes on the top and bottom edges to zero (traction free)
% TOP EDGE
topEdgeNodes = find(node(:,2)==c); % finds nodes on the top edge
f(topEdgeNodes)=0;
f(topEdgeNodes+numnode)=0;
% BOTTOM EDGE
bottomEdgeNodes = find(node(:,2)==-c); % finds nodes on the bottom edge
f(bottomEdgeNodes)=0;
f(bottomEdgeNodes+numnode)=0;
nn=length(sctr);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% COMPUTE B MATRIX
% _ _
% | N_1,x N_2,x ... 0 0 ... |
% B = | 0 0 ... N_1,y N_2,y ... |
% | N_1,y N_2,y ... N_1,x N_2,x ... |
% - -
B=zeros(3,2*nn);
B(1,1:nn) = dNdx(:,1)';
B(2,nn+1:2*nn) = dNdx(:,2)';
B(3,1:nn) = dNdx(:,2)';
B(3,nn+1:2*nn) = dNdx(:,1)';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% COMPUTE ELEMENT STIFFNESS AT QUADRATURE
POINT K(sctrB,sctrB)=K(sctrB,sctrB)+B'*C*B*W(q)*det(J0);
18
end % of element loop
%%%%%%%%%%%%%%%%%%% END OF STIFFNESS MATRIX COMPUTATION %%%%%%%%%%%%%%%%%%%%%%
% SOLVE SYSTEM
disp([num2str(toc),' SOLVING SYSTEM'])
U=K\f;
%******************************************************************************
%*** POST - PROCESSING ***
%****************************************************************************** %
% Here we plot the stresses and displacements of the solution. As with the
% mesh generation section we don't go into too much detail - use help
% 'function name' to get more details.
disp([num2str(toc),' POST-PROCESSING'])
dispNorm=L/max(sqrt(U(xs).^2+U(ys).^2));
scaleFact=0.1*dispNorm;
fn=1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PLOT DEFORMED
DISPLACEMENT PLOT figure(fn)
clf
plot_field(node+scaleFact*[U(xs) U(ys)],element,elemType,U(ys)); hold on
plot_mesh(node+scaleFact*[U(xs) U(ys)],element,elemType,'g.-');
plot_mesh(node,element,elemType,'w--');
colorbar
fn=fn+1;
title('DEFORMED DISPLACEMENT IN Y-DIRECTION')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% COMPUTE STRESS
stress=zeros(numelem,size(element,2),3);
19
stressPoints=[0 0;1 0;0 1];
end
sctr=element(e,:);
sctrB=[sctr sctr+numnode];
nn=length(sctr);
for q=1:nn
pt=stressPoints(q,:); % stress point
[N,dNdxi]=lagrange_basis(elemType,pt); % element shape functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% COMPUTE B MATRIX
B=zeros(3,2*nn);
B(1,1:nn) = dNdx(:,1)';
B(2,nn+1:2*nn) = dNdx(:,2)';
B(3,1:nn) = dNdx(:,2)';
B(3,nn+1:2*nn) = dNdx(:,1)';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% COMPUTE ELEMENT STRAIN AND STRESS AT
STRESS POINT strain=B*U(sctrB);
stress(e,q,:)=C*strain;
end
end % of element loop
stressComp=1;
figure(fn)
clf
plot_field(node+scaleFact*[U(xs) U(ys)],element,elemType,stress(:,:,stressComp)); hold on
plot_mesh(node+scaleFact*[U(xs) U(ys)],element,elemType,'g.-');
plot_mesh(node,element,elemType,'w--'); colorbar
fn=fn+1;
title('DEFORMED STRESS PLOT, BENDING COMPONENT')
%print(fn,'-djpeg90',['beam_',elemType,'_sigma',num2str(stressComp),'.jpg'])
20
C Example: Modal Analysis of an Atomic Force
Microscopy (AFM) Tip
The program presented here is found at
http://www.tam.northwestern.edu/jfc795/Matlab/Examples
/Static/modal afm.m
In addition the mesh le afm.msh is needed. This mesh le is produced
using the GPL program Gmsh which is available at
http://www.geuz.org/gmsh/
This program is not needed to run this program, only the *.msh le is
needed, but it is a very good program for generating nite element
meshes. In this example we perform a linear modal analysis of the AFM
tip shown in Fig-ure re g:afm. This involves computing the mass and sti
ness matrix and solving the following Eigenvalue problem
K !n2M an = 0 (26)
for the natural frequencies !n and the corresponding mode shapes an.
Here the AFM tip is modeled with eight node brick elements and we
assume that the feet of the AFM tip are xed.
% modal_afm.m
%
% by Jack Chessa
% Northwestern University
%
clear
colordef black
state = 0;
%******************************************************************************
%*** INPUT ***
%******************************************************************************
tic;
disp('************************************************')
disp('*** STARTING RUN ***')
disp('************************************************')
disp([num2str(toc),' START'])
% MATERIAL PROPERTIES
E0 = 160; % Youngs modulus in GPa
nu0 = 0.27; % Poisson ratio
rho = 2.330e-9; % density in 10e12 Kg/m^3
% MESH PARAMETERS
quadType='GAUSS';
quadOrder=2;
% GMSH PARAMETERS
fileName='afm.msh';
domainID=50;
21
fixedID=51;
topID=52;
%******************************************************************************
%*** PRE-PROCESSING ***
%******************************************************************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %
plot_mesh(node,element,elemType{domainID},'r-')
disp([num2str(toc),' INITIALIZING DATA STRUCTURES'])
numnode=size(node,1); % number of nodes
numelem=size(element,1); % number of elements
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% COMPUTE COMPLIANCE MATRIX
C=zeros(6,6);
C(1:3,1:3)=E0/(1+nu0)/(1-2*nu0)*[ 1-nu0 nu0 nu0;
nu0 1-nu0 nu0;
nu0 nu0 1-nu0 ];
C(4:6,4:6)=E0/(1+nu0)*eye(3);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%******************************************************************************
%*** PROCESSING ***
%******************************************************************************
22
%%%%%%%%%%%%%%%%%%%%% COMPUTE SYSTEM MATRICIES %%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp([num2str(toc),' COMPUTING STIFFNESS AND MASS MATRIX'])
[W,Q]=quadrature(quadOrder,quadType,3); % define quadrature rule
et=elemType{domainID};
nn=size(element,2);
for e=1:numelem % start of element loop
if (detJ0 <= 0)
disp(['ERROR: NEGATIVE JACOBIAN IN ELEMENT ',num2str(e)]);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% COMPUTE B MATRIX
B0=zeros(6,3*nn);
B0(1,1:nn) = dNdx(:,1)';
B0(2,nn+1:2*nn) = dNdx(:,2)';
B0(3,2*nn+1:3*nn) = dNdx(:,3)';
B0(4,2*nn+1:3*nn) = dNdx(:,2)';
B0(4,nn+1:2*nn) = dNdx(:,3)';
B0(5,1:nn) = dNdx(:,3)';
B0(5,2*nn+1:3*nn) = dNdx(:,1)';
B0(6,nn+1:2*nn) = dNdx(:,1)';
B0(6,1:nn) = dNdx(:,2)';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
23
activeDof=setdiff([1:numnode]',[fixedNodeX;fixedNodeY;fixedNodeZ]);
activeDof=[activeDof;activeDof+numnode;activeDof+2*numnode];
% SOLVE SYSTEM
disp([num2str(toc),' SOLVING EIGEN PROBLEM'])
if ( consistentMass )
[modeShape,freq]=eigs(K(activeDof,activeDof),M(activeDof,activeDof),...
numberOfModes,0);
else
Minv=spdiags(1./M,0,3*numnode,3*numnode);
K=Minv*K;
[modeShape,freq]=eigs(K(activeDof,activeDof),numberOfModes,0);
end
freq=diag(freq)/(2*pi); % frequency in kHz
%******************************************************************************
%*** POST - PROCESSING ***
%******************************************************************************
disp([num2str(toc),' POST-PROCESSING'])
disp(['THE MODE FREQUENCIES ARE:'])
for m=1:length(freq)
disp([' MODE: ',num2str(m),' ',num2str(freq(m))])
axis off
print(m, '-djpeg90', ['afm_mode_',num2str(m),'.jpg']);
end
% ANIMATE MODE
nCycles=5; % number of cycles to animate
fpc=10; % frames per cycle
fact=sin(linspace(0,2*pi,fpc));
m=input('What mode would you like to animate (type 0 to exit) '); while (
m~=0 )
U=zeros(numnode,1);
U(activeDof)=modeShape(:,m);
wt=20/max(abs(U));
for i=1:fpc
scaleFactor=fact(i)*wt;
figure(length(freq+1));
clf;
plot_field(node+[U(1:numnode) U(numnode+1:2*numnode)
U(2*numnode+1:3*numnode)]*scaleFactor,topSurface,elemType{topID},...
ones(3*numnode,1));
hold on
plot_mesh(node+[U(1:numnode) U(numnode+1:2*numnode)
U(2*numnode+1:3*numnode)]*scaleFactor,topSurface,elemType{topID},'k-');
24
plot_mesh(node,topSurface,elemType{topID},'w-');
hold on
view(37,36)
axis([70 240 30 160 -10 10])
title(['MODE ',num2str(m),', FREQUENCY = ',num2str(freq(m)),' [kHz]'])
axis off
film(i)=getframe;
end
movie(film,nCycles);
m=input('What mode would you like to animate (type 0 to exit) '); if ( m >
length(freq) )
disp(['mode must be less than ',num2str(length(freq))])
end
end
% compute uexact
25
D Common Matlab Functions
Here is a quick list of some built in Matlab functions. These discriptions
are availible by using the help function in Matlab.
>> help
HELP topics:
26
mutools/subs - Mu-Analysis and Synthesis Toolbox -- Supplement
toolbox/ncd - Nonlinear Control Design Toolbox.
nnet/nnet - Neural Network Toolbox.
nnet/nndemos - Neural Network Demonstrations and Applications.
toolbox/optim - Optimization Toolbox.
toolbox/robust - Robust Control Toolbox.
toolbox/signal - Signal Processing Toolbox.
toolbox/splines - Spline Toolbox.
toolbox/stats - Statistics Toolbox.
toolbox/symbolic - Symbolic Math Toolbox.
toolbox/wavbox - (No table of contents file)
simulink/simulink - SIMULINK model analysis and construction functions.
simulink/blocks - SIMULINK block library.
simulink/simdemos - SIMULINK demonstrations and samples.
toolbox/codegen - Real-Time Workshop
Elementary matrices.
zeros - Zeros matrix.
ones - Ones matrix.
eye - Identity matrix.
rand - Uniformly distributed random numbers.
randn - Normally distributed random numbers.
linspace - Linearly spaced vector.
logspace - Logarithmically spaced vector.
meshgrid - X and Y arrays for 3-D plots.
: - Regularly spaced vector.
27
NaN - Not-a-Number.
flops - Count of floating point operations.
nargin - Number of function input arguments.
nargout - Number of function output arguments.
computer - Computer type.
isieee - True for computers with IEEE arithmetic.
isstudent - True for the Student Edition.
why - Succinct answer.
version - MATLAB version number.
Matrix manipulation.
diag - Create or extract diagonals.
fliplr - Flip matrix in the left/right direction.
flipud - Flip matrix in the up/down direction.
reshape - Change size.
rot90 - Rotate matrix 90 degrees.
tril - Extract lower triangular part.
triu - Extract upper triangular part.
: - Index into matrix, rearrange matrix.
Specialized matrices.
28
toeplitz - Toeplitz matrix.
vander - Vandermonde matrix.
wilkinson - Wilkinson's eigenvalue test matrix.
Trigonometric.
sin - Sine.
sinh - Hyperbolic sine.
asin - Inverse sine.
asinh - Inverse hyperbolic sine.
cos - Cosine.
cosh - Hyperbolic cosine.
acos - Inverse cosine.
acosh - Inverse hyperbolic cosine.
tan - Tangent.
tanh - Hyperbolic tangent.
atan - Inverse tangent.
atan2 - Four quadrant inverse tangent.
atanh - Inverse hyperbolic tangent.
sec - Secant.
sech - Hyperbolic secant.
asec - Inverse secant.
asech - Inverse hyperbolic secant.
csc - Cosecant.
csch - Hyperbolic cosecant.
acsc - Inverse cosecant.
acsch - Inverse hyperbolic cosecant.
cot - Cotangent.
coth - Hyperbolic cotangent.
acot - Inverse cotangent.
acoth - Inverse hyperbolic cotangent.
Exponential.
exp - Exponential.
log - Natural logarithm.
log10 - Common logarithm.
sqrt - Square root.
29
Complex.
abs - Absolute value.
angle - Phase angle.
conj - Complex conjugate.
imag - Complex imaginary part.
real - Complex real part.
Numeric.
fix - Round towards zero.
floor - Round towards minus infinity.
ceil - Round towards plus infinity.
round - Round towards nearest integer.
rem - Remainder after division.
sign - Signum function.
30
rat - Rational approximation.
rats - Rational output.
cart2sph - Transform from Cartesian to spherical coordinates.
cart2pol - Transform from Cartesian to polar coordinates.
pol2cart - Transform from polar to Cartesian coordinates.
sph2cart - Transform from spherical to Cartesian coordinates.
Matrix analysis.
cond - Matrix condition number.
norm - Matrix or vector norm.
rcond - LINPACK reciprocal condition estimator.
rank - Number of linearly independent rows or columns.
det - Determinant.
trace - Sum of diagonal elements.
null - Null space.
orth - Orthogonalization.
rref - Reduced row echelon form.
Linear equations.
\ and / - Linear equation solution; use "help slash".
chol - Cholesky factorization.
lu - Factors from Gaussian elimination.
inv - Matrix inverse.
qr - Orthogonal-triangular decomposition.
qrdelete - Delete a column from the QR factorization.
qrinsert - Insert a column in the QR factorization.
nnls - Non-negative least-squares.
pinv - Pseudoinverse.
lscov - Least squares in the presence of known covariance.
31
cdf2rdf - Complex diagonal form to real block diagonal form.
schur - Schur decomposition.
balance - Diagonal scaling to improve eigenvalue accuracy.
svd - Singular value decomposition.
Matrix functions.
expm - Matrix exponential.
expm1 - M-file implementation of expm.
expm2 - Matrix exponential via Taylor series.
expm3 - Matrix exponential via eigenvalues and eigenvectors.
logm - Matrix logarithm.
sqrtm - Matrix square root.
funm - Evaluate general matrix function.
32
cd - Change current working directory.
dir - Directory listing.
delete - Delete file.
getenv - Get environment value.
! - Execute operating system command.
unix - Execute operating system command & return result.
diary - Save text of MATLAB session.
General information.
info - Information about MATLAB and The MathWorks, Inc.
subscribe - Become subscribing user of MATLAB.
hostid - MATLAB server host identification number.
whatsnew - Information about new features not yet documented.
ver - MATLAB, SIMULINK, and TOOLBOX version information.
33
See also The Optimization Toolbox, which has a comprehensive
set of function functions for optimizing and minimizing functions.
Polynomials.
roots - Find polynomial roots.
poly - Construct polynomial with specified roots.
polyval - Evaluate polynomial.
polyvalm - Evaluate polynomial with matrix argument.
residue - Partial-fraction expansion (residues).
polyfit - Fit polynomial to data.
polyder - Differentiate polynomial.
conv - Multiply polynomials.
deconv - Divide polynomials.
Data interpolation.
interp1 - 1-D interpolation (1-D table lookup).
interp2 - 2-D interpolation (2-D table lookup).
interpft - 1-D interpolation using FFT method.
griddata - Data gridding.
Spline interpolation.
spline - Cubic spline data interpolation.
ppval - Evaluate piecewise polynomial.
+ Plus arith
- Minus arith
* Matrix multiplication arith
.* Array multiplication arith
^ Matrix power arith
.^ Array power arith
34
\ Backslash or left division slash
/ Slash or right division slash
./ Array division slash
kron Kronecker tensor product kron
: Colon colon
() Parentheses paren
[] Brackets paren
== Equality relop
<,> Relational operators relop
& Logical AND relop
| Logical OR relop
~ Logical NOT relop
xor Logical EXCLUSIVE OR xor
Logical characteristics.
exist - Check if variables or functions are defined.
any - True if any element of vector is true.
all - True if all elements of vector are true.
find - Find indices of non-zero elements.
isnan - True for Not-A-Number.
isinf - True for infinite elements.
finite - True for finite elements.
isempty - True for empty matrix.
isreal - True for real matrix.
issparse - True for sparse matrix.
isstr - True for text string.
isglobal - True for global variables.
35
>> help lang
Control flow.
if - Conditionally execute statements.
else - Used with IF.
elseif - Used with IF.
end - Terminate the scope of FOR, WHILE and IF statements.
for - Repeat statements a specific number of times.
while - Repeat statements an indefinite number of times.
break - Terminate execution of loop.
return - Return to invoking function.
error - Display message and abort function.
Interactive input.
input - Prompt for user input.
keyboard - Invoke keyboard as if it were a Script-file.
menu - Generate menu of choices for user input.
pause - Wait for user response.
uimenu - Create user interface menu.
uicontrol - Create user interface control.
Debugging commands.
dbstop - Set breakpoint.
dbclear - Remove breakpoint.
dbcont - Resume execution.
dbdown - Change local workspace context.
dbstack - List who called whom.
dbstatus - List all breakpoints.
dbstep - Execute one or more lines.
36
dbtype - List M-file with line numbers.
dbup - Change local workspace context.
dbquit - Quit debug mode.
mexdebug - Debug MEX-files.
Graph annotation.
title - Graph title.
xlabel - X-axis label.
ylabel - Y-axis label.
text - Text annotation.
gtext - Mouse placement of text.
grid - Grid lines.
37
Line and area fill commands.
plot3 - Plot lines and points in 3-D space.
fill3 - Draw filled 3-D polygons in 3-D space.
comet3 - 3-D comet-like trajectories.
Volume visualization.
slice - Volumetric visualization plots.
Graph appearance.
view - 3-D graph viewpoint specification.
viewmtx - View transformation matrices.
hidden - Mesh hidden line removal mode.
shading - Color shading mode.
axis - Axis scaling and appearance.
caxis - Pseudocolor axis scaling.
colormap - Color look-up table.
Graph annotation.
title - Graph title.
xlabel - X-axis label.
ylabel - Y-axis label.
zlabel - Z-axis label for 3-D plots.
text - Text annotation.
38
gtext - Mouse placement of text.
grid - Grid lines.
3-D objects.
cylinder - Generate cylinder.
sphere - Generate sphere.
General.
strings - About character strings in MATLAB.
abs - Convert string to numeric values.
setstr - Convert numeric values to string.
isstr - True for string.
blanks - String of blanks.
deblank - Remove trailing blanks.
str2mat - Form text matrix from individual strings.
eval - Execute string with MATLAB expression.
String comparison.
strcmp - Compare strings.
findstr - Find one string within another.
upper - Convert string to uppercase.
lower - Convert string to lowercase.
isletter - True for letters of the alphabet.
isspace - True for white space characters.
strrep - Replace a string with another.
strtok - Find a token in a string.
39
Hexadecimal to number conversion.
hex2num - Convert hex string to IEEE floating point number.
hex2dec - Convert hex string to decimal integer.
dec2hex - Convert decimal integer to hex string.
Also the MathWorks web site has a lot of good tutorials, examples and
reference documentation.
http://www.mathworks.com
A good tutorial is at
http://www.mathworks.com/access/helpdesk/help/techdoc/
learn_matlab/learn_matlab.shtml
40
List of Figures
1 A simple nite element mesh of triangular elements . . . . . . 42
2 An example of a element force vector f e scattered into a global
force vector f . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
3 Diagram of beam used in beam bending example. The follow-
ing displacement boundary conditions are applied: ux = 0 at
the points (0; c) and (0,0), uy = 0 at (0; 0). The following
traction boundary conditions are used tx = y on x = 0 and
2
ty = P (x c2) on x = L. . . . . . . . . . . . . . . . . . . . . 44
4 AFM tip modeled in modal analysis example . . . . . . . . . . 45
41
5 6 (2,6)
3 4
1 2
(0,0)
Figure 1: A simple nite element mesh of triangular elements
42
1x
4
2x
e 3x
4x
2
5x
1x
6x
2x
1y
1y
2y
2y
3y
e 4y
f
5y
6y
f
Figure 2: An example of a element force vector f e scattered into a global
force vector f
43
y
x 2c
44
Figure 4: AFM tip modeled in modal analysis example
45