Intro Matlab
Intro Matlab
Erik Lund
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
These notes are intended for new students at the curriculum
Design of Mechanical Systems at Aalborg University, 2016.
Created September 12, 2016 using LATEX
You must bring your laptop with MATLAB installed to the lecture. AAU has a site license to
Matlab, see http://www.ekstranet.its.aau.dk/software/mathworks/download-mathworks/
Outline:
Getting started with MATLAB, slide 2
Two example programs, slide 42
Designing, coding and debugging programs, slide 55
Finite element example programs, slide 57
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
Outline
Erik Lund: Introduction to MATLAB, 2016
1 /1
pp. 1
1 / 40
pp. 2
2 / 40
pp. 3
Matrices
As indicated by the name of the software, matrices are the fundamental object of MATLAB.
Matrices can be created in many ways, and some examples are given in the following.
Let us define a 3 x 3 matrix A using the command
A = [1 2 3; 4 5 6; 7 8 9]
which yields the following output to screen
A =
1
4
7
2
5
8
3
6
9
If we had added a semi-colon at the end of the definition of A, then nothing would be output
to screen (echo is cancelled). We could also have defined A as
A = [1 2 3
4 5 6
7 8 9]
However, the use of a semi-colon at the end of each matrix row is convenient.
Note that MATLAB is case sensitive i.e., it distinguishes between A and a.
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
3 / 40
pp. 4
You dont need to bother (explicitly) with types of the variables being defined. By default,
MATLAB stores all numeric variables as double-precision floating-point values (16 digits).
Let us define a vector b of dimension 3 (3 x 1)
b =
6.5000
18.5000
30.5000
We could also define a random rectangular matrix C of dimension 3 x 3 by
C = rand(3,3)
which yields something like
C =
0.2785
0.5469
0.9575
0.9649
0.1576
0.9706
0.9572
0.4854
0.8003
4 / 40
pp. 5
D = A + C
which in this case yields
D =
1.2785
4.5469
7.9575
2.9649
5.1576
8.9706
3.9572
6.4854
9.8003
E = A * A
which yields
E =
30
66
102
36
81
126
42
96
150
5 / 40
pp. 6
f = b * b
where apostrophe ' indicates the transpose of a matrix. The result is
f =
1.3148e+03
The dot product could also be found using the built-in function
f = dot(b, b)
If we want to see the types of the variables defined, we enter
whos
which yields
Name
A
C
D
E
b
f
Size
3x3
3x3
3x3
3x3
3x1
1x1
Bytes
72
72
72
72
24
8
Class
double
double
double
double
double
double
Attributes
6 / 40
pp. 7
Output precision
We can change the output precision of numbers by the command
format long
If we compute the dot product again, the output would be
f =
1.314750000000000e+03
which illustrates the 16 digits available when using double precision. We will test the precision later on with a small example, where the so-called machine epsilon is computed.
We can change the output precision of numbers back to default using
format short
Note that these statements only affect the output precision of numbers. The calculations
are always performed with double precision accuracy.
7 / 40
pp. 8
We can easily solve linear systems of equations by using MATLABs backslash operator. If
you want to solve a linear system of equations given as Ax = b, the solution vector x is
obtained using
x = A\b
Let us define a 2 x 2 matrix A (we thereby redefine the previous 3 x 3 matrix) and a vector
b (also redefined):
x =
1.0000
0.5000
We can check the solution by computing
A*x
which yields
ans =
3
1
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
8 / 40
pp. 9
clear
In most cases it is sufficient just to clear all variables using the above command, but you
can also remove other items, see details on additional arguments to clear at
http://se.mathworks.com/help/matlab/ref/clear.html.
Often it is convenient to clear the Command Window using the command
clc
Finally, if you run some code generating figures, it might be convenient to close these by
the command
close all
9 / 40
pp. 10
zeros
eye
ones
diag
rand
A matrix of zeros
Identity matrix
A matrix of ones
Creates or extracts diagonal
Random matrix
ans =
1.0000
0
0
0
1.0000
0
0
0
1.0000
1.0000
1.0000
1.0000
0.0462
0.0971
0.8235
0.6948
0.3171
0.9502
0.0344
0.4387
0.3816
The defined matrix is not associated with any variable, and thus its just the answer of the
input that is being echoed to screen.
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
10 / 40
pp. 11
Another example of matrices built by blocks is given here. First we initialize a random matrix
A of dimension 2 x 2
A = rand(2)
which yields
A =
0.7655
0.7952
0.1869
0.4898
B =
0.7655
0.7952
0
0
0
0.1869
0.4898
0
0
0
0
0
1.0000
1.0000
1.0000
0
0
1.0000
1.0000
1.0000
0
0
1.0000
1.0000
1.0000
11 / 40
pp. 12
Colon, :
The colon is one of the most useful operators in MATLAB. It can create vectors, subscript
arrays, and specify for iterations.
The colon operator uses the following rules to create regularly spaced vectors for scalar
values i, j, and k:
j:k
j:i:k
You can use the colon to create a vector of indices to select rows, columns, or elements of
arrays, where:
A(:,j)
A(i,:)
A(:,:)
A(j:k)
A(:,j:k)
12 / 40
pp. 13
x = 1:10
which yields
x =
1
10
A = [1 2 3; 4 5 6; 7 8 9]
which yields
A =
1
4
7
2
5
8
3
6
9
A(3,:)
which yields
ans =
7
13 / 40
pp. 14
A(:,2)
which yields
ans =
2
5
8
A(1:2,:)
which yields
ans =
1
4
2
5
3
6
A(2:3,2:3)
which yields
ans =
5
8
6
9
14 / 40
pp. 15
f = [1 2];
for i = 3:10
% Loop for i = 3 to i = 10 using default increment of 1
f(i) = f(i-1) + f(i-2); % Compute the next number f(i)
end
f
% Echo f to screen
which yields
f =
1
13
21
34
55
89
Note how the size of f is changed inside the loop. This is actually not very efficient from a
computational point of view, but its convenient :-)
Such a loop will run much faster, if f is initialized to maximum size initially.
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
15 / 40
pp. 16
We can also change the increment of the variable being looped, for example
j = 1;
for i = 1:3:10
iVal(j) = i;
j = j + 1;
end
iVal
%
%
%
%
Initialize counter j to 1
Loop for i = 1 to i = 10 using increments of 3
Store the value of i in iVal
Increase the counter j
which yields
iVal =
1
10
If you run
for v = 1.0:-0.2:0.6
disp(v)
end
the output will be
1
0.8000
0.6000
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
16 / 40
pp. 17
Quite often it is necessary to repeat statements based on a condition rather than a fixed
number of times.
In such cases we use while loops:
z = 10;
while z > 1
z = z/2
end
which yields
z =
5
z =
2.5000
z =
1.2500
z =
0.6250
17 / 40
pp. 18
Relations
Some relation operators are given below:
<
>
<=
>=
==
Less than
Larger than
Less or equal than
Larger or equal than
Equal to
Not equal to
and
or
not
k = [4 5 2 5 11 12] > 10
which yields
k =
0
1
Getting started with MATLAB
Erik Lund: Introduction to MATLAB, 2016
18 / 40
pp. 19
Conditional statements: if
Later when we look at programming with MATLAB, it is often needed to have conditional
statements, like if and switch. An example of if is given here (taken from MATLABs help).
First we define a matrix of ones.
for c = 1:nCols
for r = 1:nRows
if r == c
A(r,c) = 2;
elseif abs(r-c) == 1
A(r,c) = -1;
else
A(r,c) = 0;
end
end
end
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
19 / 40
pp. 20
We can check the values of A by clicking on A in the Workspace inside MATLAB, thereby
starting the Variables Viewer:
A =
2
-1
0
0
-1
2
-1
0
0
-1
2
-1
0
0
-1
2
0
0
0
-1
0
0
0
0
Now, this was actually a larger number of lines that we ended up with. It is convenient to
store these lines in a script file, and in the directory Conditional a script file IfExample.m
can be loaded and executed (open the file and click Run) :-)
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
20 / 40
pp. 21
21 / 40
pp. 22
function f = Factorial(n)
f = prod(1:n);
You save the file in your working directory, and you may now call this function as, e.g.
Factorial(7)
ans =
5040
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
22 / 40
pp. 23
The general syntax when writing a function entitled FunctionName is the following:
23 / 40
pp. 24
ApproxOne = eps + 1;
Iter = 0;
while ApproxOne > 1
eps = eps * 0.5;
ApproxOne = eps + 1;
Iter = Iter + 1;
end
If you run the script you get something like
24 / 40
pp. 25
grade = B;
switch(grade)
case A
disp(Excellent!);
case B
disp(Well done);
case F
disp(Better try again);
otherwise
disp(Invalid grade);
end
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
25 / 40
pp. 26
Scalar functions
Some of the MATLAB functions that can only be applied to scalars are listed here:
sin
cos
tan
asin
acos
atan
sind
cosd
tand
exp
log
rem
abs
sqrt
sign
round
floor
ceil
A = rand(3,4)
B = sin(A)
which yields something like
A =
0.5853
0.2238
0.7513
0.2551
0.5060
0.6991
0.8909
0.9593
0.5472
0.1386
0.1493
0.2575
0.5524
0.2219
0.6826
0.2523
0.4846
0.6435
0.7776
0.8188
0.5203
0.1382
0.1487
0.2547
B =
26 / 40
pp. 27
Vector functions
Some of the MATLAB functions that can only be applied to vectors are listed here:
max
min
sum
prod
median
mean
any
all
If we consider the example vector x=1:10, the following code computes the sum and mean
values.
x=1:10
x =
1
10
sum(x)
ans =
55
mean(x)
ans =
5.5000
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
27 / 40
pp. 28
Matrix functions
Some of the MATLAB functions that can only be applied to matrices are listed here:
eig
chol
inv
lu
qr
schur
poly
det
size
norm
cond
rank
28 / 40
pp. 29
A = rand(2)
which yields
A =
0.8407
0.2543
0.8143
0.2435
y = eig(A)
which in this case yields
y =
1.0864
-0.0021
29 / 40
pp. 30
[V, D] = eig(A)
which in this case yields
V =
0.9574
0.2888
-0.6948
0.7192
1.0864
0
0
-0.0021
D =
Thus, functions in MATLAB may have a varying number of outputs. If we look at the documentation for the eig command, we see that it actually can have up to three outputs:
e = eig(A) returns a column vector containing the eigenvalues of square matrix A.
[V,D] = eig(A) returns diagonal matrix D of eigenvalues and matrix V whose columns are
the corresponding right eigenvectors, so that A*V = V*D.
[V,D,W] = eig(A) also returns full matrix W whose columns are the corresponding left eigenvectors, so that W*A = D*W.
30 / 40
pp. 31
Plotting
Finally, let us see a few plotting commands that well often use. The command plot can
produce simple 2D plots, e.g.:
x = 0:0.01:2*pi
y = sin(x);
plot(x,y)
This gives us the plot shown in Figure 2.
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0
31 / 40
pp. 32
If you want to insert title, legends, etc., then the following graphics commands can be used:
title
xlabel
ylabel
axis([xmin xmax ymin ymax])
axis auto
axis equal
axis off
axis on
Title
x-axis label
y-axis label
Sets limits to axis
Automatic limits
Same scale for both axes
Removes scale
Scales again
x = 0:0.01:2*pi
y = sin(x);
MyPlot(x, y, My sinus curve, x, y, sin)
Note that LaTeX commands can be used for the text :-)
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
32 / 40
pp. 33
33 / 40
pp. 34
The figure obtained using SinPlot.m (located in the Plot directory) is given below
My sinus curve
sin
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0
34 / 40
pp. 35
You may also create 3D plots using the command plot3. This code (Helix.m) plots a 3-D
helix:
t = 0:pi/50:10*pi;
st = sin(t);
ct = cos(t);
figure
plot3(st,ct,t)
40
30
20
10
0
1
0.5
1
0.5
-0.5
-0.5
-1
-1
35 / 40
pp. 36
You may create surface plots using the command surf (SurfPlot.m):
x=-2:.1:2;
[xx,yy]=meshgrid(x,x);
z=exp(-xx.^2-yy.^2);
surf(xx,yy,z,gradient(z))
colormap jet
colorbar
%
%
%
%
%
%
x is 1x41 matrix
xx and yy are 41x41 matrices
note: .^ for element-by-element operations
Surface plot of z (gradient(z) for colors)
Specify the color map to use
Add color bar
0.08
0.06
0.04
0.8
0.6
0.02
0.4
0.2
-0.02
0
2
-0.04
-0.06
-1
-1
-2
-0.08
-2
36 / 40
pp. 37
Symbolic expressions
Symbolic expressions can be used in Matlab, however, this is not the focus here.
A simple example is included, where the gradient vector c and the hessian H are determined
for the function f given as f (x1, x2) = 10x41 20x21x2 + 10x22 + x21 2x1 + 5:
syms x1 x2 f c H
f = 10*x1^4 - 20*x1^2*x2 + 10*x2^2 + x1^2 - 2*x1 + 5
c = gradient(f)
H = hessian(f)
which yields (try to run Symbolic.m)
f =
10*x1^4 - 20*x1^2*x2 + x1^2 - 2*x1 + 10*x2^2 + 5
c =
2*x1 - 40*x1*x2 + 40*x1^3 - 2
- 20*x1^2 + 20*x2
H =
[ 120*x1^2 - 40*x2 + 2, -40*x1]
[
-40*x1,
20]
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
37 / 40
pp. 38
38 / 40
pp. 39
Thus, the first time you run your code, it might be slow. The following times the JIT compiled
code from the first run is reused, and thus speed is increased significantly. However, loops
in MATLAB are slow and should be avoided, if speed is of concern. This is illustrated by
the script SpeedTest.m (located in directory SpeedTest).
39 / 40
pp. 40
SpeedTest.m continued:
40 / 40
pp. 41
1 / 13
pp. 42
2 / 13
pp. 43
A small illustrative example of a statically determined 3-bar planar truss defined by Figure
8 is treated.
The 3-bar truss is subjected to a vertical load F of value 1000 N in node 1 and a static
analysis of the structure can determine the unknown internal bar forces (N12, N13, N23) and
reaction forces (R2x, R2y , R3y ). Internal bar forces in tension are considered positive.
The static equilibrium equations are set up using free body diagrams.
F
F
1
L12 = 3 m
N12
L 13 = 4 m
2
y
L 23 = 5 m
N13
R 2x 2
R 2y
N23
3
R 3y
3 / 13
pp. 44
The static equilibrium equations express the fact that the sum of the x- and y -components
of the forces at each of the three joints must be equal to zero. Thus, the governing equations are:
P
P Fx = 0 :
P Fy = 0 :
P Fx = 0 :
P Fy = 0 :
P Fx = 0 :
Fy = 0 :
This is a linear system of equations with 6 unknowns, and it can be written in matrix form
as
cos
sin
cos
sin
0
0
0 cos 0 0 0
0 sin 0 0 0
1
0
1 0 0
0
0
0 1 0
1 cos 0 0 0
0 sin 0 0 1
0
N12
1000
N
23
0
N13
=
0
R2x
0
R
2y
0
R3y
4 / 13
pp. 45
A MATLAB program TrussExample.m for the solution of the 3-bar truss example is given
below:
%
%
%
%
%
sin_a
cos_a
sin_b
cos_b
=
=
=
=
4/5;
3/5;
3/5;
4/5;
% Coefficient matrix
A = [ -cos_a 0 cos_b
-sin_a 0 -sin_b
cos_a 1
0
sin_a 0
0
0 -1 -cos_b
0
0 sin_b
0
0
1
0
0
0
0
0
0
1
0
0
0
0
0
0
0
1 ];
5 / 13
pp. 46
TrussExample.m continued:
Solution:
N_l2 N_23 N_l3 R_2x R_2y R_3y
-800 480 -600
0 640 360
6 / 13
pp. 47
7 / 13
pp. 48
For this example, the result is computed by three finite difference equations, one each for
height y , velocity v , and acceleration a at the discrete time step denoted i + 1:
yi+1 = yi + vi t
vi+1 = vi + ai t
2
mg sign(vi+1)kdvi+1
ai+1 =
m
in which
CD
A
kd =
2
r:
m:
CD :
radius of softball
mass of softball
drag coefficient of sphere
density of air
4.85 cm
0.185 kg
0.5
1.29 kg/m3
For each time step we evaluate the three equations and we continue the simulation until
the ball returns to the ground.
8 / 13
pp. 49
9 / 13
pp. 50
Softball.m continued:
10 / 13
pp. 51
Softball.m continued:
11 / 13
pp. 52
t_impact = 3.6580
v_impact = -16.2043
y_apogee = 16.3931
The graphs of position, velocity and acceleration are given below.
y [m]
20
0
20
0.5
1.5
2.5
3.5
0.5
1.5
2.5
3.5
0.5
1.5
2
t [s]
2.5
3.5
v [m/s]
20
0
20
a [m/s2]
5
10
15
12 / 13
pp. 53
It should be noted that the above example code has not been written for fast execution.
In general, if you would like to have efficient MATLAB code, then you should pre-allocate
vectors and matrices, such that MATLAB does not have to re-allocate every time the size
of a vector/matrix is changed.
In the above example, the four vectors in the while loop are re-allocated every time a new
value is computed, and this takes much longer time than doing the actual computation!
Thus, we could have improved the speed dramatically by initializing the four vectors of
sufficient size. e.g.:
nMaxTimeSteps = 10000;
y = zeros(nMaxTimeSteps,1);
v = zeros(nMaxTimeSteps,1);
t = zeros(nMaxTimeSteps,1);
a = zeros(nMaxTimeSteps,1);
This is implemented in SoftballSpeedImproved.m.
13 / 13
pp. 54
1 /2
pp. 55
Below please find some good advises for developing programs that other people should be
able to read:
An incremental approach to writing programs should be adopted, i.e., you should always
break the code down to small functions (subroutines), each with a single and logical
purpose with well-defined input and output.
Dont build your house without foundations, i.e., use an incremental debugging approach where the lowest-level subroutines are tested first, then the procedures that
use them are tested, and so on until the whole program is verified.
Use representative (and thereby often long) names for programs, variables, and functions (subroutines), then the actual program written in a specific language can be very
similar to the pseudo-code.
Use comments liberally. They are invaluable when you (or others) ask why did I do
that?.
Keep the length of functions(subroutines) as low as possible, 50 lines of code (excluding
comments) are often regarded as maximum length of a specific function (subroutine).
2 /2
pp. 56
d
dT
k
dx
dx
dV +
S dV = 0
(1)
1 / 16
pp. 57
For each 1D finite element linear shape functions are used, see Fig. 10.
T4
T3
T1
N1(x)
T1 N1
T1
T2
T2
3
1
1
x1=0
x2
x3
x4
1
A1
(a)
1
N2(x)
A2
L
LT
2
T2 N2
(b)
(c)
Lx
x
T =
T1 + T2 or in matrix-vector notation:
L
L
2
X
Lx x
T1
e
e
and {T } =
T = N {T } =
NiTi where N =
T2
L
L
i=1
(2)
2 / 16
pp. 58
[K e] {T e} = {Qe}
(3)
[K e] =
Ak
L
1 1
1 1
(4)
{Q } =
|Aqx,1|
|Aqx,2|
N T S A dx
(5)
where qx,i denotes flux at node i and |A qx| is the amount of heat flow.
We only get contributions to {Qe} if qx or S are given!
Thus, for a problem with prescribed temperatures at both ends as the only boundary condition, the thermal load vector is simply a zero vector.
3 / 16
pp. 59
Equation 3 should hold for all finite elements in the model, and we therefore expand the
system of equations to the whole model by introducing the global heat conductivity matrix
[K], the global temperature vector {T } and the global thermal load vector {Q}:
[K] {T } = {Q}
where
[K] =
nX
Elem
[K e] , {Q} =
e=1
nX
Elem
{Qe}
(6)
e=1
where nElem denotes the number of finite elements in the model and {T } contains the
temperature for all nodes in the model. This summation of element contributions is normally
called assembly.
When we solve the equations, we have prescribed temperatures at one or more nodes
(stored in the vector {T p}), and the algebraic system of equations to solve can be written
as
[K pp] [K pf ]
[K f p] [K f f ]
{T p}
{T f }
{Qp}
{Qf }
(7)
The indices f and p refer to free and prescribed variables, respectively. Due to symmetry
we have that [K f p] = [K pf ]T and in general we can make use of symmetry when solving
the global system of equations (only half of the matrix needs to be stored). When solving
for free (unknown) temperatures {T f } we thus solve
[K f f ]{T f } = {Qf } [K f p] {T p}
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
(8)
4 / 16
pp. 60
Having defined the equations to be solved, we can consider a simple benchmark example.
We will consider the 1D example defined by Figure 11. The example describes source-free
heat conduction of an insulated rod where the ends are maintained at constant temperatures of 100C and 500C, respectively. The thermal conductivity coefficient is constant and
given as k = 1000 W/(m K). The cross sectional area is constant and given as A = 10 103
m2.
0.5 m
B
x
TA = 100
Area (A)
TB = 500
2
2
1
L
3
3
4
4
5
5
TB
5 / 16
pp. 61
First we need to define the bookkeeping of the problem, i.e., define the equation numbers
associated with all finite element nodes in the model.
In order to define the equation numbers of both free nodes (nodes 2, 3, 4 and 5) and
prescribed nodes (nodes 1 and 6), we loop over all nodes and define the corresponding
equation number.
In order to distinguish between free equations (f) and prescribed equations (p), we introduce positive equation numbers for free variables and negative equation numbers for prescribed variables. The global vector DOF (Degrees-Of-Freedom) containing the equation
numbers thus become:
[-1]
[1]
[2]
[3]
[4]
TB
[-2]
6 / 16
pp. 62
Thus, when assembling the system of equations by looping over all 5 elements in the
model, we know where to add each entry of the element matrix [K e] to the partitioned
system of equations given by Eqs. 7 and 8.
The element conductivity matrix is given by Eq. 4, i.e. for this model the components in
[K e], e = 1, . . . , 5, are A k/L:
[K e] =
e
K11
e
K21
e
K12
e
K22
Ak
L
1 1
1 1
100 100
100 100
For each element we use the vector DOF in order to figure out where to add the contributions for the given element.
For example, for element 1 the two element nodes are associated with global nodes 1 and
2, where node 1 has the first prescribed DOF and node 2 has the first free DOF. Similarly,
element 2 is associated with global nodes 2 and 3, where node 2 has the first free DOF
and node 3 has the second free DOF.
7 / 16
pp. 63
If we assemble the full system of equations manually by looping over all five elements, the
following symbolic expression is obtained:
p(1) f (1)
f (2)
f (3)
f (4)
p(2)
1
1
1
K12
0
0
0
0
Q1
T1
p(1) K11
1
1
2
2
1
2
Q2 + Q1
0
0
0
K12
T2
f (1) K21 K22 + K11
2
2
3
3
2
3
Q2 + Q1
K21
0
0 T3
K22 + K11
K12
f (2) 0
3
4
3
4
T 4 = Q3 + Q4
K
+
K
0
0
0
K
K
f (3)
2
21
11
1
22
12
4
4
5
5
4
5
Q
0
0
K21
+ K11
+
Q
K22
K12
T
f (4) 0
5
2
1
5
5
5
Q2
0
0
0
0
K21
K22
p(2)
T6
Here indices f and p are indicated for all columns and rows of the matrix [K], and the DOF
number is given in parentheses.
However, we only need the submatrices [K f f ] and [K f p] when solving the problem. These
are given as:
ff
[K ] =
1
K22
2
K11
+
2
K21
0
0
2
K12
3
2
+ K11
K22
3
K21
0
1
K21
0
0
3
0
K12
, [K f p] = 0
3
4
4
0
K22
K12
+ K11
4
4
5
0
K22
K21
+ K11
Finite element example programs
Erik Lund: Introduction to MATLAB, 2016
0
0
0
5
K12
8 / 16
pp. 64
The resulting system of equations (shown on the previous slide) is obtained by looping over
all elements and adding the contributions. We will do this manually in the following in order
to have a detailed description. For each element e = 1, . . . , 5, we have
e
K11
e
K21
e
K12
e
K22
T1e
T2e
Qe1
Qe2
, i.e,
100 100
100 100
T1e
T2e
0
=
0
For finite element number 1 the associated element nodes are nodes 1 and 2, where node
1 has the prescribed value T1 = 100:
1
1
K11
T1 + K12
T2 = Q11
1
1
K21
T1 + K22
T2 = Q12
For finite element number 2 the associated element nodes are the free nodes 2 and 3, i.e.
2
2
K11
T2 + K12
T3 = Q21
2
2
K21
T2 + K22
T3 = Q22
9 / 16
pp. 65
100T2 100T3 = 0
100T2 + 100T3 = 0
Similarly for element number 3 with associated free nodes 3 and 4:
3
3
K11
T3 + K12
T4 = Q31
3
3
K21
T3 + K22
T4 = Q32
such that
100T3 100T4 = 0
100T3 + 100T4 = 0
such that
100T4 100T5 = 0
100T4 + 100T5 = 0
10 / 16
pp. 66
Finally, element number 5 is associated with the free node 5 and the prescribed node 6
having the value T6 = 500:
5
5
K11
T5 + K12
T6 = Q51
5
5
K21
T5 + K22
T6 = Q52
If we combine all the equations for the unknown temperatures T2, T3, T4, and T5 (all interior
nodes obtain contributions from two elements for a 1D example) we obtain
1
K22
2
K11
+
2
K21
0
0
2
K12
3
2
+ K11
K22
3
K21
0
0
3
K12
4
3
+ K11
K22
4
K21
1
2
1
T2
0
Q2 + Q1 K21T1
2
3
T
0
Q
+
Q
3
2
1
=
4
T4
Q32 + Q41
K12
5
5
4
5
4
T5
K22 + K11
Q2 + Q1 K12T6
Thus, the resulting system of algebraic equations when reduced as defined by Eq. 8
([K f f ]{T f } = {Qf } [K f p] {T p}) is given as
11 / 16
pp. 67
100 + 100 100
0
0
T2
0
100 100
0
T
0
0
3
0
100 100 + 100 100
T
0
0
0
0
100 100 + 100
T5
0
100 500
Thus, we have
10000
T2
200 100 0
0
50000
T5
0
0 100 200
which yields
T2
180
T3
260
=
T
340
T5
420
If we change the number of finite elements, the procedure is exactly the same, only the
numbers and the amount of equations will change.
12 / 16
pp. 68
A Matlab code FEM_1D_Ex1.m for solving this example is in the directory FEM. Several
subroutines are defined as separate m-files, such that it is easy to reuse the functions for
other examples.
The matrix-vector product [K f p] {T p} is computed at the element level when assembling
[K f f ] in order to avoid storing the matrix [K f p]. The vector [K f p] {T p} is stored in a vector
called Kfp_Mult_Tp.
The result of the Matlab program is shown on Figure 14, where the finite element solution
is compared to the analytical solution. As expected, exact numerical values are obtained
for this simple example.
500
450
400
T [Celcius]
350
Analytical
FEM
300
250
200
150
100
0.1
0.2
0.3
0.4
0.5
x [m]
Figure 14: Comparison between finite element solution and analytical solution.
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
13 / 16
pp. 69
TB
TA
t
y
x
Figure 15: 1D problem. The temperature distribution is indicated on the cross section.
We need to add code for computing the element thermal load vector:
{Qe} =
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark
N T S A dx
14 / 16
pp. 70
Lx x
N =
L
L
and integrate, we obtain the element thermal load vector:
{Qe} =
L
2
(L
x)
SA
2L
L
2
x
SA
2L
0
S AL
S AL
We add a function HeatVector1D.m to our files from the previous example, and the problem
can thereby be computed using the file FEM_1D_Source.m.
The results obtained using different
discretizations (5and 10 elements) are compared with
the analytical solution T =
TB TA S
+ (t x) x + TA in Figure 16.
t
2k
15 / 16
pp. 71
300
300
Analytical
FEM
260
260
240
240
220
220
200
180
200
180
160
160
140
140
120
120
100
0.005
0.01
x [m]
0.015
Analytical
FEM
280
T [Celcius]
T [Celcius]
280
0.02
100
0.005
0.01
x [m]
0.015
0.02
Figure 16: Comparison between finite element solutions and analytical solution.
These two finite element programs have illustrated how you can create more elaborate
programs in MATLAB using detailed descriptions of the problem to be solved, detailed
pseudo code and benchmark problem in terms of setting up the problem by hand first, and
finally the MATLAB programming where a number of functions is used in order to make it
easy to reuse and expand the code. Actually, with the general bookkeeping applied, it is
easy to expand this part to 2D or 3D problems.
16 / 16
pp. 72