Finite Element Programming With MATLAB: 12.1 Using MATLAB For FEM
Finite Element Programming With MATLAB: 12.1 Using MATLAB For FEM
with MATLAB
1. the data structure of the finite element program will be periodically updated to
reflect emerging finite element technologies and MATLAB syntax changes;
2. to allow the course instructors to use their own MALAB or other finite element
codes.
3. to create a forum where students and instructors would exchange ideas and place
alternative finite element program data structures. The forum is hosted at
http://1coursefem.blogspot.com/
1
May not be covered in the class. Recommended as independent reading.
Figure 12.1: Matlab Windows
2
12.1.5 Functions
MATLAB has many standard mathematical functions such as sine (sin(x)) and cosine
(cos(x)) etc. It also has software packages, called toolboxes, with specialized functions
for specific topics.
• Type “help” in the command line: MATLAB returns a list of topics for which it has
functions. At the bottom of the list it tells you how to get more information about a
topic. As an example, if you type “help sqrt” and MATLAB will return a list of
functions available for the square root.
Bold letters will denote matrices or vectors. The elements of a matrix a are denoted by
, where i is the row number and j is the column number. Note that in both describing
the dimension of the matrix and in the subscripts identifying the row and column number,
the row number is always placed first.
An example of a 3x3 matrix is:
3
The above matrix a is is an example of a square matrix since the number of rows and
columns are equal.
The following commands show how to enter matrices in MATLAB (>> is the
MATLAB prompt; it may be different with different computers or different versions of
MATLAB.)
Notice that rows of a matrix are separated by semicolons, while the entries on a row are
separated by spaces (or commas). The order of matrix can be determined from
The transpose of any matrix is obtained by interchanging rows and columns. So for
example, the transpose of a is:
In MATLAB, single subscript matrices are considered row matrices, or row vectors.
Therefore, a column vector in MATLAB is defined by
4
Note the transpose that is used to define b as a column matrix. The components of the
vector b are . The transpose of b is a row vector
or in MATLAB
A matrix is called a diagonal matrix if only the diagonal components are nonzero,
i.e., . For example, the matrix below is a diagonal matrix:
A diagonal matrix where all diagonal components are equal to one is called an identity or
unit matrix and is denoted by I. For example, identity matrix is given by
5
The MATLAB expression for an order n unit matrix is
A matrix in which all components are zero is called a zero matrix and is denoted by 0. In
MATLAB, B = zeros (m, n) creates matrix B of zeros. A random matrix can
be created by rand (m,n).
In finite element method, matrices are often sparse, i.e., they contain many zeros.
MATLAB has the ability to store and manipulate sparse matrices, which greatly increases
its usefulness for realistic problems. The command sparse (m, n) stores an zero
matrix in a sparse format, in which only the nonzero entries and their locations are sorted.
The nonzero entries can then be entered one-by-one or in a loop.
Notice that the display in any MATLAB statement can be suppressed by ending the line
with a semicolon.
if the matrix is not singular. The MATLAB expression for the inverse is . Linear
algebraic equations can also be solved by using backslash operator as shown in Section
1.3.10, which avoids computations of the inverse and is therefore faster.
The matrix is nonsingular if its determinant, denoted by , is not equal to
zero. A determinant of a 2x2 matrix is defined by
6
The MATLAB expression for the determinant is
For example,
7
Multiplication
8
Note the the i,j entry of c is the scalar product of row i of a and column j of b.
The product of two matrices a and b c is defined only if the number of columns in
a equals the number of rows in a. In other words, if a is an matrix, then
b must be an matrix, where k is arbitrary. The product c will then have
the same number of rows as a and the same number of columns as b, i.e. it will be
an matrix.
9
We can rewrite this system of equations in matrix notation as follows:
where
The symbolic solution of the above system of equation can be found by multiplying both
sides with inverse of K, which yields
or
10
As mentioned before, the backslash provides a faster way to solve equations and should
always be used for large systems. The reason for this is that the backslash uses
elimination to solve with one right hand side, whereas determining the inverse of an nxn
matrix involves solving the system with n right hand sides. Therefore, the backslash
should always be used for solving large system of equations.
MATLAB variables can also be defined as string variables. A string character is a text
surrounded by single quotes. For example:
It is also possible to create a list of strings by creating a matrix in which each row is a
separate string. As with all standard matrices, the rows must be of the same length. Thus:
11
Strings are used for defining file names, plot titles, and data formats. Special built-in
string manipulation functions are available in MATLAB that allow you to work with
strings. In the MATALB codes provided in the book we make use of strings to compare
functions. For example the function strcmpi compares two strings
A true statment results in 1 and a false statement in 0. To get a list of all the built-in
MATLAB functions type
Another function used in the codes is fprintf. This function allows the user to print to the
screen (or to a file) strings and numeric information in a tabulated fasion. For example
The first argument to the function tells MATLAB to print the message to the screen. The
second argument is a string, where %d defines a decimal character with the value of 10
and the \n defines a new line. To get a complete description type
12
12.1.11.1 Conditional and Loops
MATLAB has a standard if-elseif-else conditional.
The general form An example
>> t = 0.76;
if expression1
>> if t > 0.75
statements1
s = 0;
elseif expression2
elseif t < 0.25
statements2
s = 1;
…
else
…
s = 1-2*(t-0.25);
…
end
else
>> s
statements
s=
end
0
12.1.11.2 Functions
Functions allow the user to create new MATLAB commands. A function is defined in an
m-file that begins with a line of the following form:
The rest of the m-file consists of ordinary MATLAB commands computing the values of
the outputs and performing other desired actions. Below is a simple example of a
function that computes the quadratic function . The following
commands should be stored in the file fcn.m (the name of the function within MATLAB
is the name of the m-file, without the extension)
13
12.1.12 Basic graphics
MATLAB is an excellent tool for visualizing and plotting results. To plot a graph the user
specifies the x coordinate vector and y coordinate vector using the following syntax
Various line types, plot symbols and colors may be obtained with plot(x,y,s) where s is a
character string consisting of elements from any combination of the following 3 columns:
14
To add a title, x and y labels, or a grid, the user should use the following MATLAB
functions. Note that the arguments to the functions are strings
In the MATLAB Finite Element code provided in the book, we also use two specialized
plots. The first plot is the patch function. This function is used to visualize 2D polygons
with colors. The colors are interpolated from nodes of the polygon to create a colored
surface. The following example generates a filled square. The colors along the x axis are
the same while the colors along the y axis are interpolated between the values [0,1].
We will use the patch function to visualize temperatures, stresses and other variables
obtained at the finite element solutions. Another specialized plot function is the quiver.
This function is used to visualize gradients of functions as an arrow plot. The following
15
example demonstrates the use of quiver function for plotting the gradients to the function
y=x2
The hold on command is used to hold the current plot and all axis properties so that
subsequent graphing commands will executed on the existing graph.
Using the text function, the user can add to a plot a text message. For example
The first and second arguments define the position of the text on the plot, while the
string gives the text.
12.1.13 Remarks
a) In practice the number of equations n can be very large. PCs can today solve
thousands of equations in a matter of minutes if they are sparse (as they are in
FEM analysis-you will learn about this later) but sometimes millions of
equations are needed, as for an aircraft carrier or a full model of an aircraft;
parallel computers are then needed.
b) Efficient solution techniques that take advantage of the sparsity and other
advantageous properties of FEM equations are essential for treating even
16
moderately large systems. The issue of how to efficiently solve large systems
will not be considered in this course.
c) In this course, we will see that
The matrix corresponding to the system of equations arising from
FEM (denoted as K) is non-singular (often called regular), i.e.,
exists if the correct boundary conditions are prescribed and the
elements are properly formulated. Furthermore, for good models it is
usually well-conditioned, which means it is not very sensitive to
roundoff errors.
K is symmetric, i.e. .
K is positive definite, i.e., (meaning for any value of x)
Alternatively, K is said to be positive definite if all the eigenvalues are
strictly positive. The eigenvalue problem consists of finding nonzero
eigenvectors and the corresponding eigenvalues satisfying
17
1. Preprocessing including input data and assembling the proper arrays, vectors,
and matrices.
2. Calculation of element stiffness matrices and force vectors
3. Direct assembly of matrices and vectors
4. Partition and solution
5. Postprocessing for secondary variables
Explanation for various MATLAB routines (stored in *.m files) are described as
comments within each subroutine.
18
d: global displacement vector is stored as:
e: element number
ke: element stiffness matrix
de: element nodal displacement vector:
=de = de
When ndof = 1 (see example in Figure 2.8) IEN and LM are defined as follows:
= IEN = LM
When ndof = 2 (example Problem 2.2), IEN and LM are defined as:
19
= IEN = LM
In both examples, columns indicate the elements and rows indicate global degrees-of-
freedom.
Remark: In this chapter nodes where the displacements are prescribed have to be
numbered first.
truss.m
%%%%%%%%%%%%%%%%%%%%%%
% 2D Truss (Chapter 2) %
% Haim Waisman, Rensselaer %
%%%%%%%%%%%%%%%%%%%%%%
clear all;
close all;
% Preprocessor Phase
[K,f,d] = preprocessor;
% Solution Phase
[d,f_E] = solvedr(K,f,d);
% Postprocessor Phase
postprocessor(d)
20
include_flags.m
% file to include global variables
global nsd ndof nnp nel nen neq nd
global CArea E leng phi
global plot_truss plot_nod plot_stress
global LM IEN x y stress
preprocessor.m
% preprocessing– read input data and set up mesh information
function [K,f,d] = preprocessor;
include_flags;
% generate LM array
for e = 1:nel
for j = 1:nen
for m = 1:ndof
ind = (j-1)*ndof + m;
LM(ind,e) = ndof*IEN(j,e) - ndof + m;
end
end
end
input_file_example2_2.m
% Input Data for Example 2.2
nsd = 2; % Number of space dimensions
ndof = 2; % Number of degrees-of-freedom per node
nnp = 3; % Number of nodal points
nel = 2; % Number of elements
nen = 2; % Number of element nodes
% Element properties
CArea = [1 1 ]; % Elements area
leng = [1 sqrt(2)]; % Elements length
phi = [90 45 ]; % Angle
E = [1 1 ]; % Young’s Modulus
% prescribed displacements
% displacement d1x d1y d2x d2y
d = [0 0 0 0]';
nd = 4; % Number of prescribed displacement degrees-of-freedom
21
% prescribed forces
f(5) = 10; % Force at node 3 in the x-direction
f(6) = 0; % Force at node 3 in the y-direction
% output plots
plot_truss = 'yes';
plot_nod= 'yes';
% mesh Generation
truss_mesh_2_2;
truss_mesh_2_2.m
% geometry and connectivity for example 2.2
function truss_mesh_2_2
include_flags;
% connectivity array
IEN = [1 2
3 3];
% plot truss
plottruss;
input_file_example2_8.m
% Input Data from Chapter 2 Figure 2.8
nsd = 1; % Number of spatial dimensions
ndof = 1; % Number of degrees-of-freedom per node
nnp = 3; % Total number of global nodes
nel = 2; % Total number of elements
nen = 2; % Number of nodes in each element
% Element properties
CArea = [.5 1]; % Elements cross-sectional area
leng = [2 2]; % Elements length
E = [1 1]; % Young’s Modulus
% prescribed displacements
d(1) = 0;
nd = 1; % Number of prescribed displacement degrees of freedom
% prescribed forces
22
f(3) = 10; % force at node 3 in the x-direction
% output controls
plot_truss = 'yes';
plot_nod = 'yes';
% mesh generation
truss_mesh_2_8;
truss_mesh_2_8.m
% geometry and connectivity for example problem in Figure 2.8
function truss_mesh_2_8;
include_flags;
% connectivity array
IEN = [1 2
2 3];
% plot truss
plottruss;
Plottruss.m
% function to plot the elements, global node numbers and print mesh parameters
function plottruss;
include_flags;
23
fprintf(1,'No. of Equations %d \n\n',neq);
trusselem.m
% generate the element stiffness matrix for each element
function ke = trusselem(e)
include_flags;
if ndof == 1
ke = const * [1 -1 ; % 1-D stiffness
-1 1];
elseif ndof == 2
p = phi(e)*pi/180; % Converts degrees to radians
s = sin(p); c = cos(p);
s2 = s^2; c2 = c^2;
end
assembly.m
% assemble element stiffness matrix
function K = assembly(K,e,ke)
include_flags;
solvedr.m
% partition and solve the system of equations
function [d,f_E] = solvedr(K,f,d)
include_flags;
24
% solve for d_F
d_F =K_F\( f_F - K_EF'* d_E);
postprocessor.m
% postprocessing function
function postprocesser(d)
include_flags;
fprintf(1,'%d\t\t\t%f\n',e,stress(e));
end
25
N: array of shape functions
B: array of derivatives of the shape functions
gp: array of position of Gauss points in the parent element domain -
W: array of weights -
Nmatrix1D.m
% shape functions computed in the physical coordinate - xt
function N = Nmatrix1D(xt,xe)
include_flags;
Bmatrix1D.m
% derivative of the shape functions computed in the physical coordinate - xt
function B = Bmatrix1D(xt,xe)
include_flags;
gauss.m
% get gauss points in the parent element domain [-1, 1] and the corresponding weights
function [w,gp] = gauss(ngp)
if ngp == 1
26
gp = 0;
w = 2;
elseif ngp == 2
gp = [-0.57735027, 0.57735027];
w = [1, 1];
elseif ngp == 3
gp = [-0.7745966692, 0.7745966692, 0.0];
w = [0.5555555556, 0.5555555556, 0.8888888889];
end
Explanation for various MATLAB routines is given as comments within each function.
Only the nomenclature and definitions which have been modified from the previous
chapters are included below. Much of the code is either identical or very similar to the
code developed in Section 12.2. An input file for the Example 5.2 in Chapter 5 modeled
with two quadratic elements is given below. Additional input files for one quadratic
element mesh and four quadratic elements mesh are provided in the disk.
27
E: vector of nodal values of Young’s modulus
CArea: vector of nodal values of cross-sectional area
flags: Flag array denoting essential and natural boundary conditions
Calculated by FE program:
ID: Destination array
bar1D.m
%%%%%%%%%%%%%%%%%%
% 1D FEM Program (Chapter 5) %
% Haim Waisman, Rensselaer %
%%%%%%%%%%%%%%%%%%
clear all;
close all;
28
% include global variables
include_flags;
% Preprocessing
[K,f,d] = preprocessor;
% Postprocessing
postprocessor(d);
include_flags.m
% Include global variables
global nsd ndof nnp nel nen neq nd CArea E
global flags ID IEN LM body x y
global xp P ngp xplot n_bc e_bc np
global plot_bar plot_nod nplot
preprocessor.m
% preprocessing– reads input data and sets up mesh information
function [K,f,d] = preprocessor;
include_flags;
input_file5_2_2ele.m
% Input Data for Example 5.2 (2 elements)
29
nnp = 5; % number of nodal points
nel = 2; % number of elements
nen = 3; % number of element nodes
% gauss integration
ngp = 2; % number of gauss points
% point forces
P = 24; % array of point forces
xp = 5; % array of coordinates where point forces are applied
np = 1; % number of point forces
% output plots
plot_bar = 'yes';
plot_nod = 'yes';
nplot = nnp*10; % number of points in the element to plot displacements and stresses
% mesh generation
bar_mesh5_2_2ele;
bar_mesh5_2_2ele.m
function bar_mesh5_2_2ele
include_flags;
% Node: 1 2 3 4 5
x = [2.0 3.5 5.0 5.5 6.0 ]; % x coordinate
y = 2*x; % y is used only for the bar plot
% connectivity array
30
IEN = [1 3
2 4
3 5];
plotbar;
setup_ID_LM.m
% setup ID and LM arrays
function d = setup_ID_LM(d);
include_flags;
count = 0; count1 = 0;
for i = 1:neq
if flags(i) == 2 % check if essential boundary
count = count + 1;
ID(i) = count; % number first the nodes on essential boundary
d(count)= e_bc(i); % store the reordered values of essential B.C
else
count1 = count1 + 1;
ID(i) = nd + count1;
end
end
for i = 1:nel
for j = 1:nen
LM(j,i)=ID(IEN(j,i)); % create the LM matrix
end
end
barelem.m
% generate element stiffness matrix and element nodal body force vector
function [ke, fe] = barelem(e);
include_flags;
for i = 1:ngp
xt = 0.5*(xe(1)+xe(nen))+J*gp(i); % Compute Gauss points in physical coordinates
31
fe = fe + w(i)*N'*be; % compute element nodal body force vector
end
ke = J*ke;
fe = J*fe;
assembly.m
% assemble element stiffness matrix and nodal force vector
function [K,f] = assembly(K,f,e,ke,fe)
include_flags;
naturalBC.m
% compute and assemble nodal boundary force vector
function f = naturalBC(f);
include_flags;
for i = 1:nnp
if flags(i) == 1
node = ID(i);
f(node) = f(node) + CArea(node)*n_bc(node);
end
end
postprocessor.m
% postprocessing
function postprocessor(d)
include_flags;
32
% loop over elements to compute the stresses
for e = 1:nel
% compute stresses and displacements for the current element
disp_and_stress(e,d);
end
33