Recitation Session

advertisement
EE4314 Lab 1 Session
Matlab and Simulink
Spring 2014
TA: Joe Sanford
joe.sanford@mavs.uta.edu
(with special thanks to Suresh Sampathkumar and Md Ahsan Habib)
MATLAB Overview
• When MATLAB launched, Command Window Appears
• Command prompt(>>) in Command Windows to accept instruction or input
• Objects → Data
• Objects are placed in MATLAB workspace
>> a = 4; b = 3+2j; c = a * b;
• whos → Another way to view workspace
>> whos
• who → short version of whos -> reports only the names of workspace objects
>> who
• clear a → remove specific variables (a) from the workspace
>> clear a
• clc → clears the command window
>> clc
• help -> most important and useful command for new users
>> help whos
• exit -> terminates MATLAB
Algebra of Complex Numbers
• Complex number: z = a + jb
• Re z = a; Im z = b
• Complex number expressed in polar coordinates (r,θ)
• a = rcos θ, b = rsin θ, z = r(cos θ+ jsin θ)
• Euler Formulae:
•ejθ=cos θ + jsin θ, z = r ejθ
• z = |z|ej∠z
• |z| = r = √(a2+ b2)
• ∠z = θ = tan-1 (b/a), π≥ θ ≥-π
• Conjugate of z, z* = a – jb = r e-jθ= |z|e-j∠z
• zz* = (a+jb)(a-jb) = a2 + b2 = |z|2
• Useful Identities (7)
• e∓jnπ = -1, n → odd integer ⇨ e∓j(2n+1)π = -1, n → integer
•e∓j2nπ = 1, n → integer
Complex Numbers – A common mistake
z1 = a +jb
θ1
∠ z1 = tan-1(b/a) = θ1
∠ z2 = tan-1(-b/-a) = θ2
∠ z2 ≠ ∠ z1
∠ z2 = θ2 = θ1 - 180
θ2
z2=-a -jb
z1 = -a +jb
θ1
θ2
z2=a -jb
Example B.1
(9)
∠ z1 = tan-1(b/-a) = θ1
∠ z2 = tan-1(-b/a) = θ2
∠ z1 ≠ ∠ z2
∠ z1 = θ1 = 180 + θ2
Complex Numbers - MATLAB
• Matlab predefines i = j =
>> z = -3-j4
• real and imag operators extract real and imaginary components of z.
>> z_real = real(z)
>> z_imag = imag(z)
• Modulus or Magnitude of a complex number
•
>> z_mag = sqrt(z_real^2+z_imag^2)
• |z|2 = zz*
>> z_mag = sqrt(z*conj(z))
>> z_mag = abs(z)
• Angle of a complex number
>> z_rad = atan2(z_mag, z_real)
• atan2 -> two-argument arc-tangent function; ensures the angle
reflects in the proper quadrant.
>> z_rad = angle(z)
• MATLAB function pol2cart number polar form to Cartesian form
• z = 4 e-j(3π/4)
>> [z_real, z_imag] = pol2cart(-3*pi/4,4)
Complex Numbers - Exercise
• Determine z1z2 and z1/z2 if z1 = 3+j4 and z2 = 2+3j (13)
>> Verify your results using MATLAB
• Convert your results from Cartesian coordinates to Polar coordinates
>> Verify your results using MATLAB function pol2cart
MATLAB - Vector Operation
• Vectors of even valued integers
>> k = 0:2:11
• Negative and non-integer step sizes
>> k = 11:-10/3:0
• If step size not specified, value of one assumed
>> k = 0:11
• In MATLAB, ascending positive integer indices specify particular vector elements.
>> k(5), k(1:4),
• Vector representation to create signals
• 10 Hz sinusoid described by f(t) = sin(2π10t+π/6) when 0≤t<0.2
>> t = 0:0.0004:0.2-0.0004; f = sin(2*pi*10*t+pi/6); f(1)
• Find the three cube roots of minus 1,
•
→
>> k = 0:2;
>> w = exp(j*(pi/3 + 2*pi*k/3))
Exercise (56)
• Find the 50th cube root of minus 1?
Simple Plotting
• MATLAB’s plot command
>> plot(t,f);
• Axis labels are added using xlabel and ylabel
>> xlabel(‘t’); ylabel(‘f(t)’)
• Plotting discrete points, 100 unique roots of w^100=-1
>> plot(real(w), imag(w), ‘o’);
>> xlabel(‘Re(w)’); ylabel(‘Im(w)’);
>> axis equal
Element by Element Operations
• Multiplication, Division and Power
• x = [5 4 6]; y = [1 2 3];
>> x_mul_y = x * y
>> x_elem_mul_y = x.*y
>> x_div_y = x/y
>> x_elem_div_y = x./y
>> x_elem_pow_y = x.^y
•Suppose h(t) = f(t)g(t) where g(t) = exp(-10*t)
>> g = exp(-10*t);
h
>> h = f.*g;
>> plot (t,f,’-k’,t,h,’-b’);
>> xlabel(‘t’); ylabel(‘Amplitude’);
>> legend (‘f(t)’,’h(t));
g(t)
Damped Sinusoid
Matrix Operations
• Common Useful function
• eye(m) creates the m×m identity matrix
>> eye(3)
•ones(m,n) creates the m×n matrix of all ones
>> ones(2,3)
•zeros(m,n) creates the m×n matrix of all zeros
>> zeros(3,2)
•Row vector
>> r = [1 3 2];
•A 2×3 matrix
>> A = [2 3; 4 5; 0 6];
Matrix Operations
• Transpose
>> c= r’;
• Concatenation
>> B = [c A];
• Matrix inverse
>> D = inv(B);
• Matrix indices
>> B(1,2)
>> B(1:2,2:3)
• Colon can be used to specify all elements along a specified
dimension
>> B(2,:)
>> B(:,2)
Matrix Operations
,
Solve
• Ax = y;
• x = A-1Ax = A-1y
>> A = [1 -2 -3; -sqrt(3) 1 –sqrt(5); 3 –sqrt(7) 1];
>> y = [1; pi; exp(1)];
>> x = inv(A)*y
Control Systems Toolbox
• Useful functions (example code to follow)
– tf(num, den) - creates a continuous-time transfer function with
numerator(s) num and denominator(s) den.
– ss(a,b,c,d) - creates the continuous-time state-space model
– impulse() - calculates the unit impulse response of a linear system.
– step() - calculates the unit step response of a linear system.
– lsim() - simulates the time response of continuous or discrete linear
systems to arbitrary inputs.
– residue(b,a) - finds the residues, poles, and direct term of a partial
fraction expansion of the ratio of two polynomials, b(s) and a(s).
– ode23() - solves initial value problems for ordinary differential
equations.
– Dsolve () – solves differential equations symbolically.
Control Systems Toolbox (exa)
• 𝐺 𝑠 =
𝑠+1
𝑠²+3𝑠+12
• How do we solve this in Matlab?
– Define variables for numerator and denominator
– Build a system
• Create a transfer function
– Show response to input
Control Systems Toolbox (exa)
>> Num = [1 1]
Num =
1 1
>> Den = [1 3 12]
Den =
1 3 12
>> sys = tf(Num, Den)
sys =
s+1
-------------s^2 + 3 s + 12
Continuous-time transfer function.
>> impulse(sys)
What about the step response?
Control Systems Toolbox (exa)
• This can also be done in a program!
– This allows you to create complex systems with
individual blocks, each with their own dynamics!
– Allows for multiple responses all at once (less
typing in command prompt)
• For example:
– Time Response to arbitrary input
>> t = 0 : 0.1 : 10;
>> u = sin(2.*t);
>> lsim(sys,u,t)
Control Systems Toolbox (cont’d)
• What about Partial Fraction Expansions?
– After defining system using Num, Den formulation
• Use “residue()” function
>> [r,p,k] = residue(Num, Den)
r=
0.5000 + 0.0801i
0.5000 - 0.0801i
p=
-1.5000 + 3.1225i
-1.5000 - 3.1225i
k=
[]
𝑠+1
𝐺 𝑠 =
𝑠² + 3𝑠 + 12
Can now be written as
𝐺 𝑠 =
.5 + .0801𝑖
.5 − .0801𝑖
+
−1.5 + 3.1225𝑖 −1.5 − 3.1225𝑖
Control Systems Toolbox - Differential
Equations
Matlab can only solve first order differential
equations
So, what do you do then?
example
𝑑2 𝑦
4
𝑚
= −𝑚𝑔 + 𝑉²
15
𝑑𝑡²
Control Systems Toolbox - Differential
Equations
• Convert Second Order system
– Introduce intermediate variable
• In this case, the first derivative of the velocity
– Divide through by the mass, m
𝑑2 𝑦
4
= −𝑔 + 𝑉²
15
𝑑𝑡²
– Then introduce intermediate variable…
Control Systems Toolbox - Differential
Equations
𝑑𝑦
𝑑𝑡
𝑑𝑧
𝑑𝑡
=
=𝑧
𝑑²𝑦
4 𝑉²
=−𝑔+
𝑑²𝑡
15 𝑚
y(0) = 600
z(0) = 0
Control Systems Toolbox - Differential
Equations
• Can use either ode45 or ode23 function
• Must give system using only first order
equations
• Let y be variable 1 and z be variable 2
• Values will be returned by ODE function in
vector form
–
dy/dt first and dz/dt second
Control Systems Toolbox - Differential
Equations
Function rk = f(t,y)
mass = 80;
g = 9.81;
rk = [y(2); -g + 4/15*y(2).^2/mass];
Control Systems Toolbox - Differential
Equations
clear all
timerange = [0 15]; %seconds
initialvalues = [600 0];
[t, y]=ode45(@f, timerange, initialvalues)
plot(t, y(:,1))
ylabel(‘height (m)’)
xlabel(‘time (s)’)
Control Systems Toolbox
• Other Useful Functions to Review
– det(sI-A)
– poles(eig A)
– ss(A,B,C,D)
– lsim(sys,u,t,x0)
Control Systems Toolbox – Stability
Example
• Define Matrices
– A = [ 0 1 0; 980 0 -2.8; 0 0 -100 ]; B = [ 0; 0; 100 ]; C = [ 1 0 0 ];
• Type in program or command window
–
–
–
–
–
–
–
–
–
–
poles = eig(A);
t = 0:0.01:2;
u = zeros(size(t));
x0 = [0.01 0 0];
sys = ss(A,B,C,0);
[y,t,x] = lsim(sys,u,t,x0);
plot(t,y)
title('Open-Loop Response to Non-Zero Initial Condition')
xlabel('Time (sec)')
ylabel(‘System Position(m)')
• What does the resultant plot show us about the system?
• What about the output of the “poles = eig(A)” command?
Control Systems Toolbox – Stability
Example
• Stability of the System
– The eigenvalues of the A matrix are the values of s
where det(sI - A) = 0.
– equivalent to the poles of the transfer fucntion
• What about the graph?
Simulink!
(very exciting stuff)
(no, really. It’s actually really, really powerful)
Simulink
• Simulink is a tool for simulating dynamic systems with a
graphical interface specially developed for this purpose
• Dynamic systems are described by differential equations.
• Simulink is a numerical differential equation solver.
• Launch Simulink by typing in Matlab command prompt
>> simulink
Create a new model
• Click the new-model
icon in the upper left
corner to start a new
Simulink file
• Select the Simulink icon
to obtain elements of
the model
Your workspace
Library of elements
Model is created in this window
Save your model
• You might create a new folder, like the one shown
below, called simulink_files
• Use the .mdl suffix when saving
Example 1: a simple model
• Build a Simulink model that solves the
differential equation
x  3 sin 2t 
• Initial condition x(0)  1.
• First, sketch a simulation diagram of this
mathematical model (equation)
Simulation diagram
• Input is the forcing function 3sin(2t)
• Output is the solution of the differential
equation x(t)
x(0)  1
3sin(2t)
(input)
x
1
s
integrator
x
x(t)
(output)
• Now build this model in Simulink
Select an input block
Drag a Sine Wave block from
the Sources library to the
model window
Select an operator block
Drag an Integrator block from
the Continuous library to the
model window
Select an output block
Drag a Scope block from the
Sinks library to the model
window
Connect blocks with signals
• Place your cursor on the
output port (>) of the
Sine Wave block
• Drag from the Sine Wave
output to the Integrator
input
• Drag from the Integrator
output to the Scope
input
Arrows indicate the direction of the
signal flow.
Select simulation parameters
Double-click on the
Sine Wave block to
set amplitude = 3
and freq = 2.
This produces the
desired input of
3sin(2t)
Select simulation parameters
Double-click on
the Integrator
block to set initial
condition = -1.
This sets our IC
x(0) = -1.
Select simulation parameters
Double-click on the
Scope to view the
simulation results
Run the simulation
In the model
window, from the
Simulation pulldown menu, select
Start
View the output
x(t) in the Scope
window.
Simulation results
To verify that this plot
represents the
solution to the
problem, solve the
equation analytically.
The analytical result,
x(t )  12  32 cos2t 
matches the plot (the
simulation result)
exactly.
Example 2
• Build a Simulink model that solves the
following differential equation
– 2nd-order mass-spring-damper system
– zero ICs
– input u(t) is a step with magnitude 1
– parameters: m = 1, c = 0.5, k = 2
(Continued)
(Continued)
• You can flip the orientation of the block by right click > Format
> Flip Block (under “Format” or hitting “Ctrl-I”
(Continued)
• The last thing we need to do is to add all the signals together
using ‘Sum’ block.
(Continued)
• At this point, the model accurately solves the ordinary
differential equation.
(Continued)
• At this point, the model accurately solves the ordinary
differential equation.
(Continued)
u(t) Signal
z(t) Signal
Introduction of Labview and
myDAQ
By: Suresh Sampathkumar
Graphical programming language
& Data flow
• LabVIEW relies on graphical symbols rather than
textual language to describe programming actions
• The principle of dataflow, in which functions execute
only after receiving the necessary data, governs
execution in a straightforward manner
How does LabVIEW work?
•
•
LabVIEW programs are called:
– Virtual Instruments (VIs)
– because their appearance and operation imitate actual
instruments.
However, they are analogous to main programs,
functions and subroutines from popular language like
C, Fortran, Pascal, …
LabVIEW Programs Are Called Virtual
• Front Panel Instruments (VIs)
• Controls = Inputs
• Indicators = Outputs
• Block Diagram
• Accompanying “program”
for front panel
• Components “wired”
together
LabVIEW Introduction
• Two “sets” for development
– Front Panel
– Block Diagram
• Wiring connections
• LabVIEW Conventions
• Running LabVIEW programs
Controls Palette
• The Controls palette contains the controls and
indicators you use to create the front panel.
LabVIEW Front Panel
• All user interfaces goes here!
• Used to display Controls or Indicators
• Highly customizable
LabVIEW Block Diagram
• Actual program
• Invisible to user
• Read left to right, like a book
• Where the MAGIC happens!
Terminals
When you place a control
(or indicator) on the
FRONT PANEL
LabVIEW
automatically
creates a
corresponding
control (or indicator)
terminal on the BLOCK
DIAGRAM
Control? or Indicator?
Controls = Inputs from the user = Source Terminals
Indicators = Outputs to the user = Destinations
Manipulating Controls and Indicators
• Right click on an indicator to
– Change to control
– Change format or precision
• Right click on a control to
– Change to indicator
– Change mechanical action (whether to latch open
or closed,
and what to use as default…)
•
Wiring
Connections
Wires transport data through the block diagram
• Wire color indicates variable type
• A red “X” means something is wrong!
Wires
A LabVIEW VI is held together by wires connecting nodes
and terminals; they deliver data from one source terminal to
one or more destination terminals.
Basic wires used in block diagrams
and corresponding types
Each wire has different style or color, depending on the data
type that flows through the wire:
Scalar
1D array
2D array
Color
Floating-point
number
orange
Integer number
blue
Boolean
green
String
pink
Dataflow Programming
• In this case, the block diagram executes from left to right, not
because the objects are placed in that order, but because the
Subtract function cannot execute until the Add function
finishes executing and passes the data to the Subtract
function. Remember that a node executes only when data are
available at all of its input terminals and supplies data to the
output terminals only when the node finishes execution.
Data Flow programming (Contd)
• consider which code segment would execute first—the Add,
Random Number, or Divide function. You cannot know
because inputs to the Add and Divide functions are available
at the same time, and the Random Number function has no
inputs.
Running LabVIEW Programs
• ALMOST ALWAYS put your
program in some sort of loop
that can be stopped with a
control
• AVOID using the red “x” to
stop your program
Select a feature to
edit or move
Add/edit text
Operate a control
Wire features together to
control flow of data
Probe Data
(troubleshoot)
Insert a boolean control
(button or switch)
Insert a digital
indicator or control
Add a numeric
operator (+,-,…)
Add a structure such as for,
while, and case statements
Comparison
Add a boolean
operator (and, or…)
Timing/dialog
File I/O
Signal analysis
Data Acquisition
Mathematical
Functions
Font ring
Continuous run
Run
Stop
Pause
Debugging features
more on this later…
Distribution ring
Alignment ring
Reorder objects
Examples
• Area of a triangle.
• Print “Hello World”.
• Connecting different data types (if time
permits)
What is MyDAQ
•
•
•
General Purpose Data Acquisition Device
Multimeter, Oscillocope, Function Generator,
Spectrometer and much more
$50-$200
+
$200
=

$300-$10,000
+
$300-$5,000
+ much more
•
MyDAQ - Designed for hands-on experimentation. NI MyDAQ combines
portability with a comprehensive set of features. NI MyDAQ allows for real
engineering and, when combined with NI LabView and Multisim, gives
students the power to prototype systems and analyze circuits in or outside of
the classroom.
•
NI MyDAQ hardware integrates with NI Labview graphical development
software, giving the students hands-on interaction with real analogue circuits,
sensor measurements, and signal processing. It bridges the gap between
theory and real-world practice by providing students with eight Labview
software-based instruments including a digital multimeter (DMM),
oscilloscope, function generator, bode analyzer, dynamic signal analyzer,
arbitrary waveform generator, digital reader and digital writer.
• NI MyDAQ is compact enough to fit in a student's pocket, and is powered by a
USB connection.
Digital Multimeter (DMM)
Measuring Resistance Across 1000Ω
Examples
• Read 5 volts from analog input using a wire.
Questions?
Download