Professional Documents
Culture Documents
Ghent University
Structural Dynamics:
MATLAB sessions
Kevin Dekemele
Chapter 1
MATLAB basics
1.1
What is MATLAB
1.2
User interface
Open MATLAB through Athena or locally (please use at least version 8.4 or 2014). When fully
loaded, the MATLAB user interface is visible, fig. 1.
2
The user interface is divided in some windows:
Current folder
This window displays the current work folder. Scripts, functions and data that you save will be
put in this folder. Also, scripts, custom functions and data that you want to use, should be in this
folder as well. Press the change current folder icon
and go to/make a folder of your choice. You
could name it for instance structdyn matlab 1.
Command window
Here, a prompt is presented, >>, where MATLAB commands can be typed, similar to MS-DOS
or a Linux/OS X terminal. By pressing Enter, the command is executed. A collection of MATLAB
commands can be combined in a script, see later.
Toolbar
The toolbar is split in a few tabs (such as Home, Plots and Apps) and provides shortcuts
for opening MATLAB files, importing data, creating variables,. . . . This way, you dont need to
remember each corresponding MATLAB command.
Workspace
The workspace contains all assigned variables.
1.3
Assignment statements
Unlike programming languages as Java and C++, but just like Python , you dont need to specify
the type which is assigned to a variable (as string, boolean, integer, double,...).
1.3.1
Type the following statements in the command window and try to understand them by reading
the printed results and looking at the workspace. The % is used to add commentary, you dont
have to type this.
Listing 1.1
clear all
close all
x = 2 % scalar
y = 2+5i;
y = [1;2;2]; % column vector
y = [1 2 2] % row vector
y(1) % first element
y = [1 x x; 3 4 5*x; y] % square matrix
y(2,3) %indexing of element
3
y(2,:)
y(:,1)
c = 'Third figure' % String
u = true % Boolean
clear all deletes any variable that was present in the workspace and close all closes all
figures, possibly left be previous users. MATLAB interprets which data type you assign to a
variable, ranging from scalars and arrays to strings. In the 7th command, ; suppresses printing of
the answer. The variable can nevertheless be seen in the workspace window, just like all the others.
1.3.2
MATLAB has many built-in functions which make variable assignment a breeze. Type the following
commands in the command window and look at the result:
Listing 1.2
%filling up
1:10
1:2:10
%using a function
linspace(0,10,5)
linspace(0,10,6)
z
z
a
b
f
=
=
=
=
=
0:25:100
linspace(0,2*pi,50)
10*sin(z);
10*cos(z);
a(1:25);
The first 4 commands were not assigned to a variable. MATLAB writes this to the variable ans,
which you can find in the workspace.
The function linespace(x1,x2,n) returns an evenly spaced row vector of n length, starting from
and including x1 up to and including x2. All functions, and examples on how to use them, can be
found in the function help. This can be reached in several ways.
Type help, followed by the function name, on the command window
Search for the function in the Search Documentation found in the upper-right corner of the
toolbar
In the command window, press Shift+F1 and type in the function name
On the site of Mathworks1 , search for function
If you want to create a functionality in MATLAB, try to search these sources or the questionand-answer site for everything science, StackExchange2 , before writing your own code, as pre-built
functions may already exist.
1
2
nl.mathworks.com
http://stackexchange.com/
4
Look at the help of the following functions and test them in the command window: zeros, eye,
rand. After this, the following command should be easy to understand:
Listing 1.3
f = [eye(2,2) rand(2,3); zeros(2,4) rand(2,1)]
1.3.3
The variables a and b were assigned 50 points of respectively the sine and cosine function in Listing
1.2 . A plot of array a is constructed as follows:
Listing 1.4
figure;
plot(a);
The command figure generates an empty window in which graphical objects can be placed. The
figure is filled by typing plot(a). This command plots the 50 points in the a vector, connecting
each point through linear interpolation. Notice that the horizontal axis now indicates which value
is at which index of vector a. As a is a function of z, it is more suited to have the values of z on
the horizontal axis:
Listing 1.5
plot(z,a);
1.4
1.4.1
Operators
Scalar and boolean
The classic scalar arithmetic and logic operators are included symbolically:
addition
subtraction
multiplication
division
power
inverse(boolean)
*
/ or \
1.4.2
Matrix
A scalar can be added, subtracted, multiplied, divided and raise the power with a matrix, by using
the same symbols as tab. 1. However, when performing operations on two matrices, the dimensions
of both matrices need to be correct, as illustrated with the following examples:
Listing 1.7
g = [1 2 3; 4 5 6];
h = [7 8 9; 10 11 12];
length(g)
size(g)
g + h
g h
g*h'
g'*h
inv(h)
k = rand(3,3);
inv(k);
k2;
[V,D] = eig(k);
To achieve the correct dimensions, the matrices are often transposed '. The inverse (inv) as well
as the eigenvalues (eig) of a matrix can only be calculated from square matrices. As the help of
eig states, V contains the eigenvalues and D the eigenvectors.
The commands length and size are two different functions (look at help). The former returns
the largest dimensions and the latter returns an array of the dimensions.
6
The previously mentioned scalar operation functions as mod and sqrt also have matrix implementation. Check out the documentation on how to do this.
Other important matrix operations are element-wise operations. Using these, elements from a
matrix can be multiplied, divided or raised to the power by the same element in another matrix
of the same dimension. To make an operation element-wise, you add a . before the symbol.
For example, g.*h results in a new matrix with the elements being aij = gij hij . Other examples:
Listing 1.8
g.*h
h.*g
g./h
g.h
g.2 %Is not sqaure, regular power does not work, but elementwise does
1.5
1.5.1
All of the previous code can be joined in a script. If you run the script, all the commands in
the script will be executed line after line. For example, imagine you solved an exercise in your
Structural dynamics course and want to save the commands you, so you can review it later, or
possible alter the code. Here, you need to solve a polynomial x5 4x4 + 2x2 + 14 = 0 and rotate
on the toolbar) and
the points {x, y} = {5, 6} over an angle of 6 . Start a new script (Press
type this code:
Listing 1.9
p=[1 4 0 2 0 14];
r = roots(p)
x 0 =
y 0 =
theta
x 1 =
y 1 =
5;
6;
= pi/6;
cos(theta)* x 0 sin(theta)* y 0
sin(theta)* x 0 + cos(theta)* y 0
Notice that 3 new tabs have been added to the toolbar. Save this file in your working directory
as MyFirstScript.m. The save button
is also found on the editor tab. Next, run this script by
pressing Run
in the editor tab of the toolbar. The function roots returns the roots of a given
polynomial. Check out the help file of this function.
1.5.2
Functions
If you need to rotate other points over a different angle you could write the same code over and
over, or make your own function, reducing redundant code.
7
Create a new function (
then
For rotation, we need 3 input and 2 output variables. The function becomes:
Listing 1.11
function [x 1,y 1] = rotation(x 0,y 0,theta)
x 1 = cos(theta)* x 0 sin(theta)* y 0;
y 1 = sin(theta)* x 0 + cos(theta)* y 0;
end
1.6
Control flow
MATLAB also has control flow features for scripts, other than jumping to the next line and
executing it. The classic conditional expression if elseif else and switch case, conditional
loop while and unconditional loop for are built into MATLAB. They have to following structure:
Listing 1.13
%%Conditional expression if elseif else
if(statement1)
%code to execute if statement1 is true
elseif(statement2)
%code to execute if statement2 is true
else
%code to execute if neither is correct
end % indicates end of ifstructure
%%Switch case
%If a variable can have many cases that need be handled differently,
switchcase is cleaner structure
n = input('Enter a number: '); %prompts the user to enter a number
switch n
case 0
8
%code
case 1
%code
case 2
%code
case 3
%code
case 4
%code
otherwise
%code
if n is 0
if n is 1
if n is 2
if n is 3
if n is 4
if 0 > n > 4
end
%%While & For loops
while(statement)
%code
end
for i=0:100
%code
end
1.7
1.7.1
The whole workspace can be saved to a .MAT-file in the current folder by using the save(filename)
function. A specific variable can also be saved, by specifying the variable name,
save(filename, variablename). Make the following script and run it:
Listing 1.15
z = linspace(0,2*pi,50);
a = 2*sin(z);
9
b = 10*cos(z);
condition = true;
fig name = 'A harmonic force'
save('workspace first lesson');
g = [1 2 3; 4 5 6];
save('some matrix','g');
Assume you both want to save the angle values z and the sine value a, it is best to save them in
one variable instead of two separate. You can create an array with the 2 variables as rows or a
table can be used:
Listing 1.16
singlesine a = [z' a'] % Transpose to have 2 columns
singlesine = table(z',a','VariableNames',{'Angle','Force'});
The second approach is useful as the columns can be named. This way the variable is easier to
understand if the data is imported some time later or by somebody else. To access a column in
a table datatype, just simply type tablename.columnname. For example singlesine.Angle
returns the values of the z vector. This way, you dont need to remember in which order columns
were put in the table variable, only the name of the columns. If the first method is used, the
programmer needs to know in which columns has which data.
Add the following code to the scripts, save it and run it:
Listing 1.17
singlesine a = [z' a'] % Transpose to have 2 columns
singlesine = table(z',a','VariableNames',{'Angle','Force'});
save('singlesine data','singlesine');
It can be useful to export the data to other filetypes than .MAT, for example an excel file or a text
file. This can be done in two ways. The first, xlswrite, cannot save tables to excel but column
names can be added with some workaround. The second way, writetable, is specifically designed
for the table datatype and can save to not only Excel files. Some possible file extensions are .xls,
.xlsx, .txt, .csv.
The following code deals with both possibilities:
Listing 1.18
% writes the array to an excel file
xlswrite('singlesine raw data.xlsx', singlesine a );
% write the array, + adding names to columns
A = cell(size(singlesine a) + [1 0])
A(1,:) = {'Angle' 'Force'};
A(2:length(A),:) = num2cell([singlesine a(:,1) singlesine a(:,2)]);
xlswrite('singlesine.xlsx', A );
% write the table, same result but much easier to code
writetable(singlesine, 'singlesine table.xlsx');
10
As you can see, trying to add column names in the excel file using the arrays requires a lot of
code.3
The writetable makes this easier, as it uses the information of the table.
This again proves the advantages of tables. Add the last line of code and run the script again,
resulting in an excel file in the working directory.
1.7.2
Importing
.MAT files
Type clear all and close all to delete all variables in the workspace and close all figures.
Download the file data1.mat from Minerva and put it in the working directory. The previously
saved .MAT files can be loaded by typing the following lines one by one in the command window.
Observe the effect of each individual command:
Listing 1.19
load('workspace first lesson');
clear all;
load('workspace first lesson','fig name','condition');
load('some matrix');
load('singlesine data');
load('data1');
By specifying the filename, the variable inside the .mat file are loaded. If the file has more than
one variable, you can choose to only load certain variables, as done in the third line.
Other files
Data acquisition software often saves their measurements in a datafile. However, most of the time
the data is saved to standard .txt, .csv and .xls files instead of the MATLAB native .MAT file.
Look for the file different data source.cvs on Minerva. A CSV file (comma-separated value)
separates each value with a comma if the decimal is a dot, or with a semicolon if the decimal is a
comma4 . The latter is the case in this file. Put the CSV file in the working directory.
To import this data, MATLAB has a built-in functionality. On the home tab of the toolbar, click
the Import Data button
and select different data source.csv.
An import program is opened. For now it looks gibberish, as MATLAB assumes a comma separates
the values. Change the value of column delimiters from comma to semicolon. Also, click on
more options and change the decimal sign from . to ,. See fig. 2 for the location of these options.
Now MATLAB fully understands this foreign datafile.
3
As the array you want save has strings as first row, yet doubles for the other rows, a new kind of variable is
introduced, a cell array. A cell wraps any kind of variable, making it a cell variable. This way, different types can
be put in the same array. Here strings and doubles are put in the same array. Before the introduction of tables in
MATLAB 2014, saving to excel and using column names had to be done this way.
4
This is the standard in most of continental Europe, however not in MATLAB
11
12
1.8
Figures revisited
1.8.1
Plot Arguments
With foreign, singlesine and multisine in the workspace, lets make some elaborate figures.
Create a new script, add these lines and run it (do not clear the workspace):
Listing 1.20
figure
plot(singlesine.Angle,singlesine.Force,'or','Linewidth', 3);
By adding more arguments to the plot function, some modifications are made. The first, 'or',
adds circle markers, changes the line colour to red and the line style to a dashed one. The argument
has the form of 3 specifiers wedged together, in general form mark type color line style. Some
specifiers:
Specifier
o
+
*
s
Marker style
Circle
Plus sign
Asterisk
Square
Specifier
k
y
r
b
Colour
Black
Yellow
Red
Blue
Specifier
:
-.
Line style
Solid line
Dashed line
Dotted line
Dash-dot line
1.8.2
Plot functions
Several other functions alter the appearance of plots. They are not given as arguments to the plot
function but are typed as separate commands or functions. You have encountered some of these
before:
Listing 1.21
title(c);
xlabel('radians')
ylabel('function value')
legend('Earthquake 1','Earthquake 2')
13
Listing 1.22
grid on
grid minor
grid off
hold on
hold off
xlim[a b]
ylim[c d]
axis([a b c d])
axis off
The first three use grid. You can add major (on) and minor (minor) gridlines, and also remove
them explicitly (off).
The next two, hold, determine what happens when a new plot is added, while no new figure was
declared. If put on, the new plot will be added on the same figure as the old plot.
The last commands deal with the axis limits. xlim[a b] sets the x axis limits of the plot between
a and b, and ylim does the same for the y axis. axis can do the same in 1 command, and also
has several more options, as changing the visibility of the axis with off. For more options check
out the help function of axis.
Add the following code (with the loaded data still in the workspace) to your script and run it:
Listing 1.23
figure
plot(singlesine.Angle,singlesine.Force,'r');
hold on
plot(multisine.Angle,multisine.Force,'k');
legend('A single sine', 'A multiharmonic signal')
grid on
grid minor
axis([0 6 10 20])
%axis off
Observe the gridlines, and notice that you added a second plot and have custom x and y ranges.
The two signals however, multisine and singlesine, have a different range.
1.8.3
Multiple plots
MATLAB features several possibilities to plot several lines on the same figure. Some of which solve
the problem if two signals have different ranges.
On the same figure
Add the following lines to script:
Listing 1.24
14
figure
plot(singlesine.Angle,singlesine.Force,'r',multisine.Angle,multisine.Force, ...
'g','Linewidth', 3);
The 3 dots ... allow to split the code over multiple lines. Effectively, you did the same as before
when using hold on, but now you can add name/value arguments that have effect on both plot
lines. Observe that you can modify each plot line with the specifiers, but Linewidth is applied to
both lines although its only specified once. However, the problem is that the domain and range of
the two lines are different, which results in a biased image.
Subplots
A figure can be divided into a grid of plots. In each plot, you can change both axes. In this way,
the problem of different signal ranges is solved. A 2 by 2 grid of plots is shown on fig.4.
15
For example, to make a 3 by 1 plot grid, with the singlesine, multisine and foreign table
data, add this to your script:
Listing 1.26
%Assign data to x and y vectors, to reduce typing further on
x1 = singlesine.Angle;
y1 = singlesine.Force;
x2 = multisine.Angle;
y2 = multisine.Force;
x3 = foreign.Angle;
y3 = foreign.Force;
figure
subplot(3,1,1);
plot(x1,y1);
title('Harmonic excitation');
xlabel('Radians')
ylabel('Force')
subplot(3,1,2);
plot(x2,y2);
title('MultiHarmonic excitation');
xlabel('Radians')
ylabel('Force')
subplot(3,1,3);
plot(x3,y3);
title('Rising excitation');
xlabel('Radians')
ylabel('Force')
1.8.4
The only function discussed here to plot, was plot. Some other interesting ones are:
plotyy, plots two signals, each with its own y axis
semilogx, plots signal(s), with a logarithmic x-axis
semilogy, plots signal(s), with a logarithmic y-axis
loglog, plots signal(s), with a logarithmic x-axis and y-axis
16
For the more curious
The figure is saved with white borders. To remove this, download the saveTightFigure function
from Minerva and put it in the working directory. To save a figure, first assign the figure you are
using to plot to a variable, and after plotting:
Listing 1.27
fig1 = figure;
%plotting code
saveTightFigure(fig1, filename) %file name should be of form 'name.pdf'
1.9
1.9.1
Dynamic systems, expressed as a transfer function or a state space model can be manipulated in
.
MATLAB. For now lets only consider SDOF transfer functions of the form G(s) = B(s)
A(s)
If A(s) equals ana sna + ana 1 sna 1 + + a1 s + a0 and B(s) equals bnb snb + bnb 1 snb 1 + + b1 s + b0
then the transfer function is created in MATLAB by putting the polynomial coefficients in an array,
as seen before with the command roots. Imagine the arrays denom = [ana ana 1 . . . a0 ] and num =
[bnb bnb 1 . . . b0 ], then the transfer function in MATLAB is defined as:
Listing 1.28
system = tf([denom],[num]);
For more features of these functions, check out their documentation on the help function or Mathworks website.
1.9.2
Example
System definition
Let us consider a lightly damped structure modelled as a mass-spring-damper system. The transfer
function of this system is:
17
1
1
2
m s + 2n s + n2
G(s) =
(1)
18
As MATLAB is a numerical package, it cannot deal with continuous signals5 , so this time horizon
needs to be sampled in a time vector t. If N samples are taken for a time horizon Tl , the sample
time Ts and sample frequency fs are defined as:
Ts =
1
Tl
=
fs
N 1
(2)
Therefore, for a fixed Tl , a number of samples N or sampling time Ts needs to be chosen. Input
and output signals will only be considered on these points.
As you know from the Nyquist criterion, a continuous signal, with highest frequency component
fmax can be reconstructed from a sampled signal if the sampling frequency is at least twice this
maximal frequency:
fs 2fmax
(3)
So the sampling period should at least satisfy this condition. For instance, as 3 = 20, s should
be at least 40.
But calculate enough points, and have a smooth interpolation, its better to choose a much higher
sampling frequency.
Choose Tl = 100s and fs = 100Hz and add the following code to your script:
Listing 1.32
Fs = 100; %100 Hz
Ts = 1/Fs;
Tl = 100; % Tome horizon 100s
N = Tl*Fs + 1; %number of samples
Now the three input signals can be defined, and the system can be simulated with lsim.
Listing 1.33
u1 = sin(omega n*t);
u2 = sin(1*t);
u3 = sin(20*t);
y1=lsim(sys,u1,t);
y2=lsim(sys,u2,t);
y3=lsim(sys,u3,t);
figure
plot(t,y1,t,y2,t,y3);
legend('Slow load', 'Near resonant load','Fast load');
5
A computer can inherently not deal with continuous signal, as everything is represented digitally, i.e. discrete
in both time and value. Calculations on so called continuous signal will always feature some kind of internal
discretization.
19
Are the responses, after a transient, what you expected from theory?
On choosing time horizon
The sampling frequency fs is chosen for obvious reasons, you want the highest frequency to be
present in your sampled signal and you want to simulate the system in many points to have a nice
figure. The choice of time horizon Tl may not be immediately clear. Some guidelines are:
After an impulse or transient load (shock), a dynamical system will vibrate according to its
natural frequency. Choose Tl as such that the duration of the transient load is included plus
some periods of the free response, such that the damping effect can be evaluated.
If a harmonic load is applied, the transient has to be included in the time horizon (which
damps out with en ) as well a few steady state periods. The steady state periods period is
the same as the period of the harmonic load.
1.10
1.10.1
Problem
A building frame is modelled as two massless elastic columns with spring constant k = 0.5 106
N/m. The rigid roof has a mass m = 2000 kg (Fig. 5 ). Neighbouring mines use explosives which
X
F
K
P2
P1
T
T1
T2
Td
P1 = 2000N ;
P2 = 4000N
t1 = 0.02s ;
t2 = 0.06s ;
td = 0.08s
20
1.10.2
Matlab code
As a task, simulate the response of the building on the shock load. With some minor modifications
of the script youve just made the system can be defined. For any of the shock loadss parameters,
the input vector for the system can easily by defined as:
Listing 1.34
blast = zeros(N,1);
blast(1:td/Ts) = P1;
blast(t1/Ts:t2/Ts) = P2;
With N being the total amount of samples and Ts the sampling time (1/fs ).
In the course notes, it is stated that for short shock loads, a shock load can be seen as an impulse
response, scaled with the intensity of the load:
Z td
f (u)du
(4)
I=
0
I=
Ts
X
f (n)Ts
(5)
I
sin(n t)
mn
(6)
As a task:
Compare the response of the blast load to the impulse response. Use scaling with I as
suggested above.
Play with the parameters t1 , t2 , and most importantly td , and compare the responses again
to the scaled impulse response.
Add light damping to the system (e.g. = 0.02), compare the response of this lightly damped
system to the response of the undamped system. Compare the peak values of the response
(Home) Try to find an analytic expression for the response by applying the convolution
integral or Laplace transform. Plot the analytic expression and compare with the simulation
In this exercise, fs should be higher then in the previous script, as the time scale of the signals is
smaller as well (look at td ). A good choice is fs = 5000Hz, in this way, the duration of the pulse
td can be very short compared to the natural period of the structure.