LabVIEW MathScript
LabVIEW MathScript
MathScript
http://home.hit.no/~hansha/?page=labview
These are the main modules we use in the different
courses at Telemark University College:
• LabVIEW (LabVIEW Professional Development System 32-Bit: English)
• LabVIEW Control Design and Simulation Module
• LabVIEW MathScript RT Module
• NI-DAQmx (Hardware Driver for NI USB-6008, NI TC-01, etc.)
Note! These packages are separate downloads! Make sure to
download and install all of them!
USB-6008
Wi-Fi DAQ
Water Tank
Pt-100
TC-01
Arduino
ZigBee
Vision System
cRIO
NOx Sensor
LabVIEW
This is the core LabVIEW installation that installs
the LabVIEW Programming Environment.
NI-DAQmx
DAQmx is the Hardware Driver needed in order to use hardware
devices like NI USB-6008, NI TC-01, etc. inside LabVIEW. The module is
available as a palette on your block diagram.
What is LabVIEW MathScript?
>> x=5;
Students: Try these examples
>> X=6;
>> x+X >> x=3
x =
ans = 3
11
>> y=4;
>>
Unlike many other languages, where the semicolon is used to
terminate commands, in MATLAB the semicolon serves to
suppress the output of the line that it concludes.
MathScript Basics
>> r=5;
>> A=pi*r^2
>> a=2;
>> z1=3+3i; >> b=0;
>> z2=3+5i;
A =
>> z = z1+z2 >> a/b
78.5398
z =
6.0000 + 8.0000i
Students: Try these examples
MathScript Basics Matematical Expressions
Solutions:
>> x=2;, y=2
>> z = 3*x^2 + sqrt(x^2 + y^2) + exp(log(x))
ans =
16.8284
...
MathScript Basics
h=8 A=?
MathScript Basics
Solutions:
>> h=8
>> r=3
>> A = 2*pi*r^2 +2*pi*r*h;
A =
207.3451
Vectors & Matrices
>> b = [1:2:10]
>> b = [1:0.5:4]
Matrices
Students: Define the following
matrices in MATLAB
>> A = [1 2; 3 4]
A = 1 2
3 4
or:
Try these examples
>> A = [1, 2; 3, 4]
>> B+C
>> B-C
A = 1 2
>> B/C
3 4 >> B*C
>> B.*C
>> B'*C
...
Matrices
Given the following matrices:
>> rank(A)
>> det(A)
>> inv(A)
>> inv(B)
>> eig(A)
>> A*B >> A*(B*C) >> inv(A)
>> B*A >> (A*B)*C >> inv(B)
>> A+B >> (A+B)*C >> diag(A)
>> B' >> A*C + C*B >> inv(A)*A
>> B'*C >> (A+inv(B))*C >> A*inv(A)
>> A*B'
>> A'*B’ ... ...
>> A.*B
...
Creating Scripts
Script Editor When using the Script Editor, you may create several lines of code
and execute all in one batch. You can easily do changes in your
code, create comments, etc. clear
clc
x=0:0.1:2*pi;
y=sin(x);
y2=cos(x);
y3=tan(x);
y4=atan(x);
%plotting sin(x)
subplot(2,2,1)
plot(x,y)
%plotting cos(x)
Run the Script subplot(2,2,2)
plot(x,y2)
%plotting tan(x)
subplot(2,2,3)
plot(x,y3)
%plotting atan(x)
Students: Try this example subplot(2,2,4)
plot(x,y4)
Plotting
x = 0:5;
Example:
y(t) = 2x + 4 y = 2*x + 4;
plot(x,y)
xlabel
grid ylabel
axis
title text
Students: Try these functions
...
>> plot(x,y,'r*', x,y2,'g+')
Plotting
Plotting functions:
Name Description
Students: Try this example
plot Create a Plot >> x=0:0.1:2*pi;
figure Define a new Figure/Plot window
>> y=sin(x);
>> plot(x,y)
grid Create Grid lines in a plot
on/off >> title('Plot Example')
title Add Title to current plot >> xlabel('x')
>> ylabel('y=sin(x)')
xlabel Add a Label on the x-axis
>> grid on
ylabel Add a Label on the x-axis >> axis([0,2*pi,-1,1])
>> legend(’Temperature')
axis Set xmin,xmax,ymin,ymax
User-defined Functions
MATLAB contains hundreds of built-in functions, but very often you need to create your
own functions
Input
Function name
Return value input
Tf =
t = 0:0.1:24;
Tc = (sin(t)+1)*20;
Tf = fahrenheit(Tc);
Yes:
Use english names on variables, functions, files, etc. This is No:
common practice in programming! a=2;
Use always variables – Do not use numbers directly in the b=4; y=2+4
expressions! y=a+b
Always include these
lines in your Script
Functions: clear
• Only ONE function in each File! clc
• The Filename (.m) AND the Name of the Function MUST be close all
the same! …
Tips & Tricks Use help in order to find out
how to use a function in
Greek!letters:!In!maths!and!control!theory!it!is!common!to!use!greek! MATLAB. In order to get help
letters!in!formulas,!etc.!These!cannot!be!used!directly!in!MATLAB,!so! for the tf function, type the
you!need!to!find!other!good!alternatives.!Examples:! following in the Command
window:
!! ! –!w0!
help tf
!! –!zeta!or!just!z!
etc.!
Mathematical expressions:
The following applies in MATLAB
A Golden Rule: One Task – one file, i.e. DONT
put all the Tasks in one single file!!
x = 2;
y = 2;
z = 3*x^2 + sqrt(x^2 + y^2)+ exp(log(x))
Sorry!
• There are no “Short-Cuts” if you
want to learn LabVIEW!
(except the few shown on the previous page J)
• Practice, practice and practice!
LabVIEW Training:
1 - LabVIEW Training for Students (National
Instruments):http://www.ni.com/academic/students/learn-
labview/
2 - LabVIEW Course:
http://home.hit.no/~hansha/?training=labview
MathScript Node
You can define named inputs and outputs on the MathScript Node
border to specify the data to transfer between the graphical
LabVIEW environment and the textual MathScript code.
Using MathScript for
Simulations
Note!
Different Ts = Sampling Time
books use
different When Ts -> 0, we have a continuous signal,
notations but in a computer that is not possible.
k = 0, 1, 2, 3, 4, ....
Example
Discretization
Given the following differential equation:
Then we get:
% Simulation Parameters
Ts = 0.1; %s
Tstop = 20; %s
uk = 1;
x(1) = 0;
% Simulation
for k=1:(Tstop/Ts)
x(k+1) = (1-a*Ts).*x(k) + Ts*b*uk;
end
LabVIEW
PC
Control System
MathScript
Frequency Response
Stability Analysis
Discretization
State-space models
Building blocks:
Example: num=[1];
den=[1, 1];
H1= tf(num, den);
num=[1];
Students: Try this Example
den=[1, 1, 1];
H2 = tf(num, den);
H = series(H1,H2)
Transfer functions
MathScript code:
% Transfer Function
MathScript code: num = [2, 3];
% Transfer Function den = [1, 4, 3];
num = [4]; H = tf(num, den)
den = [2, 1];
H = tf(num, den) Try these % Step Response
examples step(H)
% Step Response
step(H)
MathScript:
A = [1, 2; 3, 4]; Step Response:
Note! The system is
B = [0; 1];
unstable
C = [1, 0];
D = [0];
model = ss(A, B, C, D)
step(model) Yes!
Can we find the transfer
Students: Try these Examples function from SS model? H = tf(model)
Students: Implement
this state-space model
in MathScript
model = ss(A, B, C, D)
step(model)
MathScript:
Hr = ...
Hp = ...
Hm = ...
MathScript:
L = ...
T = feedback(L, 1)
Det karakteristiske polynom
En transferfunksjon kan skrives på følgende generelle polynomform:
• Der telleren til transferfunksjonen beskriver nullpunktene til systemet, mens nevneren
beskriver polene til systemet.
• Røttene i tellerpolynomet b(s) kalles systemets eller transferfunksjonens nullpunkter
MathScript:
num=... num=...
den=… den=…
H = tf(num,den) H = tf(num,den)
or:
zero(H) roots(num) %Zeros
pole(H) roots(den) %Poles
Poles and Zeros - Solutions
MathScript:
%Transfer Function
num=[2,1];
den=[0.5, 2, 1];
H=tf(num,den)
%Zeros
z = zero(H)
%roots(num)
%Poles
p = pole(H)
%roots(den)
Impulse/Step Response impulse(H)
step(H)
Asymptotisk stabilt system:
Ustabilt system:
Example
T(s)
K = [1, 2, 4];
Marginalt stabilt
N = length(K);
for i= 1:N
Kp = K(i);
num = [Kp];
den = [1, 2, 1, Kp];
H = tf(num, den);
figure(i)
Ustabilt
step(H)
end
Stability Analysis – 2.order systems
Masse-Fjær-demper system
% Mass-spring-damper
clear
clc
clear all
% Define variables
Prøv ulike verdier av zeta slik m = 1;
at vi kan gjenskape de ulike d = 1;
responsene som er typisk for k = 1;
et 2.ordens system zeta= d/(2*sqrt(m*k))
% Step Response
step(H)
Solutions
m=1, k=1, d=2 -> z=1 m=1, k=1, d=0 -> z=0
-> Stabilt (Kritisk dempet) -> Marginalt stabilt
Poles
Eksempel:
MathScript:
num = [3];
den = [0.5, 1];
Stabilt H = tf(num, den)
Ustabilt
p = poles(H)
pzgraph(H)
Ustabilt system:
figure(2)
pzmap(H)
Poler:
Masse-Fjær-demper system – Eksempel - MathScript kode
% Mass-spring-damper system
clear
clc
clear all
% Define variables
Prøv ulike verdier av zeta slik at vi m = 1;d = 1; k = 1;
kan gjenskape de ulike responsene zeta= d/(2*sqrt(m*k))
som er typisk for et 2.ordens
system. % Define Transfer function
num = 1/m ;
den = [1, (d/m), (k/m)];
H = tf(num, den);
% Step Response
Metode 1 figure(1), step(H)
(Sprangrespons)
Metode 2 % Stability Analysis
(Polplassering) p = poles(H)
figure(2), pzmap(H)
Students:
Pen and paper: Find the difference equation
(discrete differenitial equation) for this
system.
Discretization Example - Solutions
Given the following continuous system:
% Model Parameters
a = 0.25;b = 2;
% Simulation Parameters
Ts = 0.1; %s
Tstop = 20; %s
uk = 1; % Step in u
x(1) = 0; % Initial value
% Simulation
for k=1:(Tstop/Ts)
x(k+1) = (1-a*Ts).*x(k) + Ts*b*uk;
end
Students:
% Plot the Simulation Results Implement and Simulate
k=0:Ts:Tstop; this system in MathScript
plot (k, x)
grid on
Discretization in MathScript - Alt. 2
% Model Parameters
a = 0.25;
b = 2;
Ts = 0.1; %s
% State-space model
A = [-a];
B = [b];
We get the same answer as in
C = [1];
D = [0];
previous example!
Students:
model = ss(A,B,C,D)
Implement and Simulate
model_discrete = c2d(model, Ts, 'forward')
this system in MathScript
step(model_discrete)
Discrete State-space Models Example
in MathScript
Given the following continuous system:
Try with different values for Ts!
MathScript
% Properties
Ts = 0.1;
% Continuous System:
A = [0, -Ts; 0, 0];
B = [2*Ts, 0]';
C = [1 0];
D = [0];
ssmodel = ss(A, B, C, D);
figure(1)
step(ssmodel)
% Discrete System:
ssmodel_discete = c2d(ssmodel, Ts, 'forward’)
figure(2)
step(ssmodel_discete)
Students: Implement the system above and find the step response using MathScript.
Frequency Response
T = 1 year
T = 24 hours
Inside Temperature
frequency 1 (year)
Assume the outdoor temperature is
varying like a sine function during a year
(frequency 1) or during 24 hours
(frequency 2).
frequency 2 (24 hours)
Then the indoor temperature will be a
sine as well, but with different gain. In
addition it will have a phase lag.
Frequency Response Example
Air Heater
Dynamic
System
Amplitude Frequency
Gain Phase Lag
(“forsterkning”) (“faseforskyvning”)
The frequency response of a system expresses how a sinusoidal signal of a given frequency on
the system input is transferred through the system.
Bode Diagram The x-scale is logarithmic
Gain (“Forsterkningen”)
The y-scale is in [dB]
𝜔𝑐
𝐿𝑜𝑔 𝜔 ω [rad/s]
∆𝐾
𝜑 𝜔180
𝐿𝑜𝑔 𝜔 ω [rad/s]
è The Bode diagram gives a simple Graphical overview of the Frequency Response for a given system.
A Tool for Analyzing the Stability properties of the Control System
Bode Diagram – MathScript Example
Given the following transfer function:
Instead of Plotting the Bode Diagram we can also use the bode function for
calculation and showing the data as well:
...
wlist = [0.01, 0.1, 1, 2 ,3 ,5 ,10,
100];[mag, phase, w] = bode(H, wlist);
magdB = 20*log10(mag); % Convert to dB
freq_data = [w, magdB, phase]
Students: Plot the Bode Diagram for the given transfer function using MathScript
Bode Diagram – MathScript Example - Solutions
or:
clear, clc
% Transfer function
num=[1];
den1=[1,0];
den2=[1,1]
den3=[1,1]
den = conv(den1,conv(den2,den3));
H = tf(num, den)
% Bode Diagram
bode(H) clear, clc
subplot(2,1,1) % Transfer function
grid on num=[1];
subplot(2,1,2) den=[1,2,1,0];
H = tf(num, den)
grid on
% Bode Diagram
bode(H)
or: subplot(2,1,1)
grid on
subplot(2,1,2)
grid on
Stability Analysis with
Frequency Response
Ustabilt system
Stability Analysis - Summary
Tidsplanet
Asymptotisk stabilt system
Frekvensrespons/Bodediagram
Ustabilt system
Ustabilt system
Stability Analysis using Frequency
Response within MathScript
Hr = ...
Hp = ...
Hm = ...
L = series(series(Hr, Hp), Hm)
bode(L)
margin(L)
[gm, pm, w180, wc] = margin(H);
gmdB = 20*log10(gm)
bode margin
Stability Analysis – MathScript Example
Students:
• Set Kp=0.5 (in this example Kp will be the loop gain).
• Plot the Bode diagram.
• Find ωc, ω180, ΔK, φ – both manually from the plot and compare with the results from
MathScript (margin function).
Stability Analysis – MathScript Example - Solutions
MathScript:
clear, clc, clf
% The Controller Transfer function Hr(s) [gm, pm, w180, wc] = margin(L);
Kp = 0.5;
Hr = tf(Kp) wc
w180
% The Loop Transfer function gmdB = 20*log10(gm)
L = series(series(Hr, Hp), Hm) pm
GM
wc
0.0 0.1
1
PM
0.1
w180
0.0
Stability Analysis – Example cont.
Results from previous page:
Kp=0.5
ΔK
Students:
• How much can we increase Kp before the system becomes unstable?
• Plot the Step Response and find the Poles for different Kp (asymtotically stable,
marginally stable, unstable)
Stability Analysis – Example cont. - Solutions
t = 0:0.1:50;
figure(4)
step(T, t)
p = poles(T)
figure(5)
pzmap(T)
Merk! Siden (alt)for dårlig stabilitet må unngås, mens (alt)for god stabilitet kan aksepteres, er de nedre
grensene for GM og PM kritiske, mens de øvre grensene er anbefalte, men ikke kritiske.
Frequency Response MathScript functions
Select one of the following Challenges
http://www.techteach.no/simview/mass_spring_damper/index.php
Students: Simulate this system using MathScript. Plot the position, speed and the
accelleration. Test with different values on m, k and d.
Air Heater
Use the bode and margin functions in MathScript to plot the frequency response in a
Bode diagram.
Find the following:
The crossover-frequencies ωc and ω180
The gain margin, GM (ΔK)
The phase margin, PM (φ)
Find the poles for the system. Draw the poles in the imaginary plane. Is the system
stable? Discuss the results.
Hans-Petter Halvorsen, M.Sc.
E-mail: [email protected]
Blog: http://home.hit.no/~hansha/