Sie sind auf Seite 1von 72

Introduction to 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

Getting started with MATLAB


MATLAB is a commercial software and a trademark of The MathWorks, Inc.
Aalborg University has bought a site license for MATLAB, and it is decided within the School
of Engineering and Science, that MATLAB should be the main programming language used
for courses, if suited for the purpose.
MATLAB (short for MATrix LABoratory) is both a
multi-paradigm numerical computing environment
programming language
MATLAB is an interpreted language i.e., you dont need to compile your code before you
can run it.
This is convenient for interactive development of numerical algorithms, and these slides
will give a quick introduction to the use of MATLAB, both as an environment for numerical
computations, thereby replacing your pocket calculator, and how you may use MATLAB as
programming language when developing programs.
This introduction to basic MATLAB functions is to some extend inspired by Chapter 1 of the
textbook by A.J.M. Ferreira (2009): MATLAB Codes for Finite Element Analysis, Springer.
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

1 / 40
pp. 2

Links to tutorials, examples, and help


There are many good web sites with tutorials, examples, etc. for MATLAB. The students
are advised to make use of these, together with the tutorials available in MATLAB and at
the web page of the developer of MATLAB: http://www.mathworks.com/.
Mathworks has a web site named Academia that you may access through your AAU
account: http://www.mathworks.se/academia/.
At the Academia website you may find many tutorials at
http://www.mathworks.se/academia/student_center/tutorials/.
You may also consider to look at the short introduction to MATLAB available at
http://se.mathworks.com/help/matlab/getting-started-with-matlab.html
You may find more than 1000 recorded MATLAB webinars at
http://se.mathworks.com/company/events/webinars/index.html.
A huge number of examples are available at MathWorks at
http://se.mathworks.com/help/matlab/examples.html.
Please note that several public domain MATLAB clones (or MATLAB compatible programs) are available. One of these free-of-use programs is the command line program
Octave (http://www.gnu.org/software/octave/) that can be used for all the examples given
in the course. Other such programs include Scilab, Rlab and Tela.
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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]


which yields

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

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

4 / 40
pp. 5

Operating with matrices


Matrices can be added, subtracted, multiplied and transposed. Having defined A and C
above, we can obtain a matrix D = A + C using

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

We can compute the matrix product E = A A as

E = A * A
which yields

E =
30
66
102

36
81
126

42
96
150

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

5 / 40
pp. 6

If we want to compute the dot product f = b b = bT b, we can input

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

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Class
double
double
double
double
double
double

Attributes

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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.

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

A = [1 4; 2 -2]; b = [3; 1]; x = A\b


which yields (note that A and b are not echoed to screen due to the semi-colons)

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

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

8 / 40
pp. 9

Clear memory, Command Window, and close figures


In the above example we redefined A and b, but sometimes we will run into trouble, if our
redefinitions dont match the previous use of variables.
The command used to remove all variables from the current workspace, releasing them
from system memory, is clear

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

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

9 / 40
pp. 10

Some useful matrix functions


These functions are convenient when defining matrices:

zeros
eye
ones
diag
rand

A matrix of zeros
Identity matrix
A matrix of ones
Creates or extracts diagonal
Random matrix

For example, a 3 x 7 matrix can be initialized as

[eye(3), diag(eye(3)), rand(3)]


which yields

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

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

We then define a matrix B of dimension 5 x 5 built by blocks as

B = [A, zeros(2,3); zeros(3,2), ones(3)]


which yields

B =
0.7655
0.7952
0
0
0

0.1869
0.4898
0
0
0

0
0
1.0000
1.0000
1.0000

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

0
0
1.0000
1.0000
1.0000

0
0
1.0000
1.0000
1.0000

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

is the same as [j,j+1,j+2,...,k]


is the same as [j,j+i,j+2i, ...,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)

is the jth column of A


is the ith row of A
is the equivalent two-dimensional matrix A.
is A(j), A(j+1),...,A(k).
is A(:,j), A(:,j+1),...,A(:,k)

Let us see some examples of using the colon operator.


Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

12 / 40
pp. 13

We can define a vector x as

x = 1:10
which yields

x =
1

10

We define a matrix A again as

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

A =
1
4
7

2
5
8

3
6
9

Let us extract some submatrices of A.

A(3,:)
which yields

ans =
7

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

14 / 40
pp. 15

Loops: for and while


Very often we have repetitive execution of a block of statements, or perhaps we have an
iterative procedure. In such cases we can use for or while loops.
An example of a for loop is the computation of the first 10 Fibonacci numbers.
The colon operator is used. Note that in MATLAB the percent symbol (%) denotes a comment and thus the rest of the line is ignored:

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

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

% Echo iVal to screen

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

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

Some logical operators are:


&
|

and
or
not

An example of using logical operators is:

k = [4 5 2 5 11 12] > 10
which yields

k =
0

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

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.

nRows = 4; nCols = 6; A = ones(nRows,nCols);


Next we loop through the matrix and assign each element a new value. Assign 2 on the
main diagonal, -1 on the adjacent diagonals, and 0 everywhere else:

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

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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:

Figure 1: The result of the loops


You may also simply type A for echoing the content of A to screen:

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

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

20 / 40
pp. 21

Debugging/running scripts with MATLAB


When you are executing and debugging the MATLAB files provided, it is convenient to use
these short keys:
F12: Insert/remove a break point
F11: Step into
F10: Step over
F5: Run to the next break point
By stepping through the code while its running, you can check the execution, the current
values of the variables, etc.
It is really important to become familiar with the debugging environment in MATLAB!
Thus, spend a few minutes on debugging the IfExample.m script.
Among others, put in break points (F12) and check the current values of variables. Notice
how MATLAB will give you the current value of a given variable, if you point at it in the editor
using the mouse pointer. Also note how the workspace contains all the variables defined.
The script starts with the following lines in order to start from scratch:

% Clear variables, screen and figures


clear; clc; close all;
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

21 / 40
pp. 22

M-files, scripts and functions


Program files can be scripts that simply execute a series of MATLAB statements, or they
can be functions (called from a script or command window) that also accept input arguments and produce output. Both scripts and functions contain MATLAB code, and both are
stored in text files with a .m extension. Thereby the name M-files is used very often.
In general functions are more flexible and more easily extensible than scripts, as they
(hopefully) have well-defined input and output. A script can be considered as a main program, if compared to notation used in other programming languages.
You create a function by opening a file in a text editor (typically the built-in editor of MATLAB) and use the same name for the function and the file. For example, if you want to
create a function Factorial that computes the factorial of an input argument n in an output argument f , you write the following in the file Factorial.m:

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

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

22 / 40
pp. 23

The general syntax when writing a function entitled FunctionName is the following:

function [ output_args ] = FunctionName( input_args )


%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
end
It is good practise to write end at the end of a function. This is for example needed, if your
file contains a main function that calls another function placed in the same file, e.g.:

function [m,s] = stat2(x)


n = length(x); m = avg(x,n); s = sqrt(sum((x-m).^2/n));
end
function m = avg(x,n)
m = sum(x)/n;
end
Try to call stat2.m (located in directory Functions) using

values = [12.7, 45.4, 98.9, 26.6, 53.1];


[ave,stdev] = stat2(values)
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

23 / 40
pp. 24

Script computing machine epsilon


Machine epsilon gives an upper bound on the relative error due to rounding in floating point
arithmetic. It normally has the Greek symbol epsilon, .
The script MachineEpsilon.m computes (denoted eps in the script) as:

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

Epsilon is: 1.1102e-16


It was found after 53 iterations
This also illustrates the 16 digits used for double precision in floating point arithmetic.

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

24 / 40
pp. 25

Conditional statements: switch


If you have many conditional statements (options), it is much easier to read the code (and
more efficient) if switch is used instead.
A switch example is given below (some of the cases are omitted for brevity):

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

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

These functions can be applied to all elements of a vector or matrix, as in

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 =

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

Eigenvalues and eigenvectors


Choleski factorization
Inverse
LU factorization
QR factorization
Schur decmposition
Characteristic polynomial
Determinant
Size of a matrix
1-norm, 2-norm, F-norm, inf -norm
Conditionining number of 2-norm
Rank of a matrix

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

28 / 40
pp. 29

An example of determining eigenvalues and eigenvectors of a matrix is given here. We


start by defining a random matrix A:

A = rand(2)
which yields

A =
0.8407
0.2543

0.8143
0.2435

If we only want the eigenvalues y, we can call eig as

y = eig(A)
which in this case yields

y =
1.0864
-0.0021

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

29 / 40
pp. 30

If we want both the eigenvalues D and eigenvectors V, we can call eig as

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

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

Figure 2: Sinus plot


Thus, you can quickly generate simple plots.
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

On the following slide a plotting function MyPlot is listed. It is defined as

function MyPlot(x, y, MyTitle, MyXLabel, MyYLabel, MyLegends)


Thus, you may call this function with your x and y data together with specifications about
title, xlabel, ylabel, and legend.
The result of the following code (SinPlot.m) is given by Figure 3.

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

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

32 / 40
pp. 33

function MyPlot(x, y, MyTitle, MyXLabel, MyYLabel, MyLegends)


% Plot the data y as function of x
close
hold on
plot(x, y);
grid on
axis xy
axis on
title(MyTitle)
xlabel(MyXLabel)
ylabel(MyYLabel)
legend(MyLegends)
MyYAxis(1,1) = 0; MyYAxis(1,2) = y(1);
MyYAxis(2,1) = 0; MyYAxis(2,2) = y(size(y,2));
line(MyYAxis(:,1),MyYAxis(:,2),linewidth,2,Color,[.0 .0 .0]);
hold off
end
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

Figure 3: Sinus plot using MyPlot


You may also have several curves in the same plot. Try running these commands (also put
in the file Plot2.m):

x=0:.01:2*pi; y1=sin(x); y2=sin(2*x); y3=sin(4*x);


plot(x,y1,--,x,y2,:,x,y3,+)
You will have to change the apostrophe signs to ' manually, if you copy the above text
from the pdf (font conversion problem). Thus, its easier to load the file Plot2.m.
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

Figure 4: Plot of 3D helix


Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

Figure 5: Surface plot


Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

37 / 40
pp. 38

Increasing the speed of MATLAB code


As stated in the beginning: MATLAB is an interpreted language i.e., you dont need to
compile your code before you can run it.
As we have seen from the above examples, this is convenient for interactive development
of code.
Students should however be aware, that MATLAB in many cases is slower than numerical
software developed using precompiled code developed in C++, C, Fortran, etc.
Experienced MATLAB users are aware of this and very often convert the computationally
intensive part of the MATLAB code to precompiled code.
MATLAB provides a C and Fortran API for programs written in these languages. These API
functions can be used in your programs and built into binary MEX-files, which you call from
the MATLAB command line. These features are, however, out of the scope of these notes
where focus is on the numerical algorithms.
In the 2015b release MATLAB introduced a new JIT (Just-In-Time) compiler. The redesigned MATLAB execution engine uses JIT compilation of all MATLAB code and generates native machine level code that is optimized for the MATLAB code being executed
and for the specific hardware platform.

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

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

tic % Start stopwatch timer


% Define matrices A, B and C of dimension 50 x 50
A = rand(50); B = rand(50); C = zeros(50,50);
% We will compute the matrix product C = A*B 1000 times using loops;
for nRuns = 1:1000
for i = 1:50
for j = 1:50
C(i,j) = 0;
for k = 1:50
C(i,j) = C(i,j) + A(i,k) * B(k,j);
end
end
end
end
toc % Stop stopwatch timer
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

39 / 40
pp. 40

SpeedTest.m continued:

tic % Start stopwatch timer


% Perform the matrix multiplications using the built-in function *
for nRuns = 1:1000
C = A*B;
end
toc % Stop stopwatch timer
If you run the program you get something like

Elapsed time is 5.123243 seconds.


Elapsed time is 0.022872 seconds.
Thus, expect that the built-in optimized functions in MATLAB are much faster than writing
them yourselves...
If you write clear all, then the precompiled code made by the JIT compiler is removed.
Therefore, in most cases you should just clear variables (by writing clear).

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Getting started with MATLAB


Erik Lund: Introduction to MATLAB, 2016

40 / 40
pp. 41

Two example programs


Reference for this section:
Jay B. Brockman: Introduction to Engineering: Modeling and Problem Solving, John Wiley
& Sons, 2009, ISBN 978-0-471-43160-2.
In order to demonstrate the use of MATLAB on some standard engineering problems, two
examples from the excellent text book by Brockman (2009) are included here. The book
gives a great introduction to modeling in engineering, and the problems considered are
solved using MATLAB.

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Two example programs


Erik Lund: Introduction to MATLAB, 2016

1 / 13
pp. 42

Static analysis of a 3-bar truss structure


Truss structures are commonly used in structural engineering and architecture due to their
superior stiffness and strength for a given amount of material.
A truss structure that consists of straight members connected by means of pin joints, and
supported at both ends by means of hinged joints or rollers, such that they cannot transfer
moments, is described as being statically determinate.
Thus, loading subjected to a truss structure results in either tensile or compressive forces
in the members, together with reaction forces at the supports.

Figure 6: Truss structure support of roof in Hamburg Airport.


Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Two example programs


Erik Lund: Introduction to MATLAB, 2016

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

Figure 7: A 3-bar truss with internal and external forces.

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Two example programs


Erik Lund: Introduction to MATLAB, 2016

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:

x-components of forces at joint 1 :


y -components of forces at joint 1 :
x-components of forces at joint 2 :
y -components of forces at joint 2 :
x-components of forces at joint 3 :
y -components of forces at joint 3 :

P
P Fx = 0 :
P Fy = 0 :
P Fx = 0 :
P Fy = 0 :
P Fx = 0 :
Fy = 0 :

cos N12 + cos N13 = 0


sin N12 sin N13 1000 = 0
cos N12 + N23 + R2x = 0
sin N12 + R2y = 0
N23 cos N13 = 0
sin N13 + R3y = 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

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

0
N12

1000
N

23

0
N13
=
0
R2x

0
R
2y

0
R3y

Two example programs


Erik Lund: Introduction to MATLAB, 2016

4 / 13
pp. 45

A MATLAB program TrussExample.m for the solution of the 3-bar truss example is given
below:

%
%
%
%
%

File TrussExample.m for the solution of 3-bar truss problem


Solves the system of equations AX = B, where
X is a column vector of unknown forces, of the form
X [N_12 N_23 N_13 R_2x R_2y R_3y]

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 ];

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Two example programs


Erik Lund: Introduction to MATLAB, 2016

5 / 13
pp. 46

TrussExample.m continued:

% Right-hand side, external forces


B = [0 1000 0 0 0 0];
% Solve for the unknown forces
X = A\B; % Use MATLABs backslash operator for solving the equation system
% Display the results in a nice format
disp(Solution:)
disp( N_l2 N_23 N_l3 R_2x R_2y R_3y) % display labels
disp(X) % Display the transpose of X
Running the MATLAB program, the following result is obtained:

Solution:
N_l2 N_23 N_l3 R_2x R_2y R_3y
-800 480 -600
0 640 360

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Two example programs


Erik Lund: Introduction to MATLAB, 2016

6 / 13
pp. 47

Modeling the trajectory of a softball with drag


The next example illustrates the use of a loop and a stopping criterion. It also demonstrates
how to generate plots. Finite difference equations are used to derive a numerical solution
for the trajectory of a softball launched vertically, including the effect of drag.
The example is described in detail in Brockman (2009). A pdf of this section is available
together with the MATLAB file in the Softball directory, if you want to see derivation of the
governing equations.

Figure 8: Trajectories of a softball, http://www.pitchsoftball.com.


Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Two example programs


Erik Lund: Introduction to MATLAB, 2016

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

with the following physical constants:

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.

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Two example programs


Erik Lund: Introduction to MATLAB, 2016

8 / 13
pp. 49

A pseudo-code description of the script is as follows:

Set physical constants


Set initial conditions
WHILE the softball altitude is greater than or equal to O
Evaluate the finite difference equations for y, v, and a
Find the maximum altitude, impact time , and impact velocity
Plot altitude, velocity, and acceleration versus time
Translating this into MATLAB, we get the following script called Softball.m:

% The program Softball.m contains a model for the trajectory of a softball


% launched vertically including the effects of drag.
clear;
% Physical constants
g = -9.81;
% acceleration [m/s^2]
r = 0.0485;
% radius of softball [m]
m = 0.185;
% mass of softball, [kg]
rho = 1.29;
% density of air [kg/m^3]
Cd = 0.5;
% drag coefficient of sphere
A = pi*r^2;
% cross-sectional area of sphere [m^2]
kd = Cd*rho*A/2; % drag force coefficient
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Two example programs


Erik Lund: Introduction to MATLAB, 2016

9 / 13
pp. 50

Softball.m continued:

% Set initial conditions


i = 1;
% i is the step number
v0 = 20; % initial velocity [m/s]
dt = .001; % time step size [s]
y(1) = 0; % altitude [m]
v(1) = v0; % velocity [m/s]
t(1) = 0; % time [s]
a(1) = (m*g - kd*v(1)^2)/m; % acceleration [m/s^2]
% Euler loop, until softball hits ground
while (y(i) >= 0)
t(i+1) = t(i) + dt;
y(i+1) = y(i) + v(i)*dt;
v(i+1) = v(i) + a(i)*dt;
a(i+1) = (m*g - sign(v(i+1))*kd*v(i+1)^2)/m;
i=i+1;
end

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Two example programs


Erik Lund: Introduction to MATLAB, 2016

10 / 13
pp. 51

Softball.m continued:

% Set final values


t_impact = t(i)
v_impact = v(i)
y_apogee = max(y)
% Generate plots
subplot(3,1,1);
plot(t,y);
ylabel(y [m]);
subplot(3,1,2);
plot(t,v);
ylabel(v [m/s]);
subplot(3,1,3);
plot(t,a);
ylabel(a [m/s^2]);
xlabel(t [s]);

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Two example programs


Erik Lund: Introduction to MATLAB, 2016

11 / 13
pp. 52

Running the MATLAB script, the following result is obtained:

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

Figure 9: MATLAB simulation of softball trajectory.

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Two example programs


Erik Lund: Introduction to MATLAB, 2016

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.

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Two example programs


Erik Lund: Introduction to MATLAB, 2016

13 / 13
pp. 54

Designing, coding and debugging programs


In generel when you develop programs/algorithms, it is important to understand, that the
development of any program consists of the following three phases:
1. The design phase , where a very large amount of the time should be spent. Pseudo-code
(flow charts, etc.) must always be written before the actual programming is done!
2. The coding phase , which is actually just a translation of the pseudo-code written in the
design phase.
3. The debugging phase , where the program is verified and, hopefully, errors are found
and corrected. The time spent in this phase very much depends on the time spent on
planning in the design phase, a few minutes of planning may easily save several hours
(days and sometimes weeks) of debugging!
Pseudo-code can be described as a detailed description of what a computer program or algorithm must do, expressed in a formally-styled natural language rather than in a programming language. The style of the pseudo-code used in the design phase when describing
a numerical algorithm very often consists of mathematical notation, for example from matrix theory, mixed with the control structures of a conventional programming language, and
perhaps also natural language descriptions.
Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Designing, coding and debugging programs


Erik Lund: Introduction to MATLAB, 2016

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

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Designing, coding and debugging programs


Erik Lund: Introduction to MATLAB, 2016

2 /2
pp. 56

Finite element example programs


Finally, an example of a finite element analysis program is given in order to illustrate, how
such a program can be decomposed to a number of tasks, solved in functions (subroutines). The examples are from a course on numerical methods given on the 3rd year of the
mechanical engineering bachelor study at AAU.
The M-files are stored in the directory FEM.
The problem considered is the 1D steady state heat conduction problem, where the governing equation is given as

d
dT
k
dx
dx

dV +

S dV = 0

(1)

Here T is temperature, S is a source term, k is the thermal conductivity coefficient, V is


volume, and x is axial coordinate for the 1D problem.
The case of having a uniform rod with constant cross sectional area A and constant thermal
conductivity is considered.

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Finite element example programs


Erik Lund: Introduction to MATLAB, 2016

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)

Figure 10: 1D element and linear shape functions Ni.


The interpolation T within a given element is thus given as

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)

where the domain of the finite element considered is 0 x L.

{T e} is the element temperature vector and N is the shape function matrix.


Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Finite element example programs


Erik Lund: Introduction to MATLAB, 2016

2 / 16
pp. 58

We can derive the discretized equations for one finite element to be

[K e] {T e} = {Qe}

(3)

The element heat conductivity matrix [K e] is defined as

[K e] =

Ak
L

1 1
1 1

(4)

The thermal element load vector {Qe} is defined as


e

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

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Finite element example programs


Erik Lund: Introduction to MATLAB, 2016

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

Finite element example programs


Erik Lund: Introduction to MATLAB, 2016

(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

Figure 11: Definition of 1D diffusion example with Dirichlet boundary conditions.


The rod is divided into 5 finite elements of equal length L = 0.1 m. We thereby have the
discretized finite element model illustrated on Figure 13.
TA

2
2

1
L

3
3

4
4

5
5

TB

Figure 12: Discretization of 1D diffusion example with Dirichlet boundary conditions.


Department of Mechanical and Manufacturing Engineering,
Aalborg University, Denmark

Finite element example programs


Erik Lund: Introduction to MATLAB, 2016

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:

{DOF } = {1, 1, 2, 3, 4, 2}T


For example, node 2 has equation number 1 whereas node 6 has the second prescribed
equation, stored as -2 in the vector.
TA
DOF

[-1]

[1]

[2]

[3]

[4]

TB

[-2]

Figure 13: 1D diffusion example with DOFs added.

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Finite element example programs


Erik Lund: Introduction to MATLAB, 2016

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 this discretization, the subvectors {T p} and {T f } are given as

{T p} = {T1, T6}T = {100, 500}T ,

{T f } = {T2, T3, T4, T5}T

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.

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Finite element example programs


Erik Lund: Introduction to MATLAB, 2016

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

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

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

Thus, the equation for node 2 becomes:


1
1
K22
T2 = Q12 K21
T1 i.e. 100T2 = 0 (100) 100

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

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Finite element example programs


Erik Lund: Introduction to MATLAB, 2016

9 / 16
pp. 65

Thus, we obtain the following two equations for element number 2

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

and for element number 4 with associated free nodes 4 and 5:


4
4
K11
T4 + K12
T5 = Q41
4
4
K21
T4 + K22
T5 = Q42

such that

100T4 100T5 = 0
100T4 + 100T5 = 0

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Finite element example programs


Erik Lund: Introduction to MATLAB, 2016

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

Thus, the equation for node 5 becomes:


5
5
K11
T5 = Q51 K12
T6 i.e. 100T5 = 0 (100) 500

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

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Finite element example programs


Erik Lund: Introduction to MATLAB, 2016

11 / 16
pp. 67


100 + 100 100
0
0
T2
0
100 100

100 100 + 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

100 200 100 0 T3


0

0 100 200 100 T4 = 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.

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Finite element example programs


Erik Lund: Introduction to MATLAB, 2016

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

Finite element example programs


Erik Lund: Introduction to MATLAB, 2016

13 / 16
pp. 69

1D steady state heat conduction problem with uniform heat generation


We consider a second finite element example. A large plate of thickness t = 2 cm has
constant thermal conductivity k = 0.5 W/(m K) and uniform heat generation S = 1000
kW/m3. The faces A and B are at temperatures 100C and 200C, respectively. Assuming
that the dimensions in the y and zdirections are so large that the temperature gradients
are significant in the xdirection only, a 1D problem can be applied.

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

Finite element example programs


Erik Lund: Introduction to MATLAB, 2016

14 / 16
pp. 70

If we insert the shape functions

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

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Finite element example programs


Erik Lund: Introduction to MATLAB, 2016

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.

Department of Mechanical and Manufacturing Engineering,


Aalborg University, Denmark

Finite element example programs


Erik Lund: Introduction to MATLAB, 2016

16 / 16
pp. 72

Das könnte Ihnen auch gefallen