Upload
steven-hertz
View
21
Download
2
Embed Size (px)
Citation preview
Get Started with MATLABand Simulink
An Introductory Tutorial
CPE111 Computer Engineering Exploration2010
Dr.Boonserm Kaewkamnerdpong
What is MATLAB?
• MAT + LAB … Matrix LaboratoryMatrix Laboratory
• Interactive system for doing numericalcomputations
• Powerful tool for calculations inscientific and engineering problems
MATLAB Components
Command WindowCommand Window
Command HistoryCommand History
WorkspaceWorkspace
MATLAB Components
MATLAB as a Calculator
• Arithmetic: >> 2 + 3 >> 3 - 2 >> 2 * 3 >> 1 / 2 >> 2 ^ 3 >> 2 \ 1
Numbers & Formats
• Integer ………………… 1362, -217897• Real …………………… -1.234, -10.76• Complex ……………… -3.21 - 4.3i• Infinity “Inf”• Not a number “NaN”
See different formats: >>help format <Enter>
Try setting format: >>format short e <Enter>
The “e” notation is used for very large or very small numbers:
-1.3412e+03 = -1.3412 × 103 = -1341.2 -1.3412e-01 = -1.3412 × 10-1= -0.13412
Variables• We can use our own names to store numbers: >> a = 2 >> b = 3 >> x = 3-2^4 >> y = x*5 >> NetCost = x + y• Variable names are case sensitive.• Avoid using special characters i.e. @, -, :, ;• Avoid using special names in mathematics i.e. pi,i, j
Suppressing Outputs
• If you don’t want to see the result ofintermediate calculations, you shouldend the expression with semi–colon.>> x=-13; y = 5*x, z = x^2+y y = -65 z = 104
Built-In Functions
• Examples:• Trigonometric Functions (sin, cos, tan,asin, acos, atan) >> x = 5*cos(pi/6), y = 5*sin(pi/6) x = 4.3301 y = 2.5000 >> acos(x/5), asin(y/5), pi/6 ans = 0.5236
• Other elementary functions:>> x = 9;>> sqrt(x), exp(x), log(sqrt(x)), log10(x^2+6)ans = 3ans = 8.1031e+03ans = 1.0986ans = 1.9395
Vectors
• Series of numbers• Types of vectors:
– Row vector >> v = [ 1 3, sqrt(5)] v = 1.0000 3.0000 2.2361
>> c = [ 1; 3; sqrt(5)] c = 1.0000 3.0000 2.2361
– Column vector
Matrices• Array of numbers• Table consisting rows and columns >> a = [1 2 3; 4 5 6] a = 1 2 3 4 5 6• Reference matrix element: >> a(2,3), a(2,1:3)• Transpose matrix >> b = a’
Arithmetic of Vectors/Matrices
>> v + 3 ans =
>> v * 3 ans =
>> v * c ans =
What about What about ““c * vc * v””??
>> c * v ans =
Arithmetic of Vectors/Matrices
>> c .* c ans =
Keeping a Record
• Saving all subsequent texts appearing on thescreen
>> diary filename
• Listing current variables>> whos
• Saving all variables in the workspace>> save filename
• Loading saved workspace>> load filename
Plotting Functions
>> x1 = linspace(0 ,2*pi,100);>> y1 = sin(3*x1);>> plot(x1,y1,’b-’)>> grid on; hold on>> N = 100; h = 1/N; x2 = 0:h:2*pi;>> y2 = 0.5*cos(x2); plot(x2,y2,’r--’)>> title(‘My First MATLAB Plot’);>> xlabel(‘x’); ylabel(‘y’);>> legend(‘sin(3x)’,’0.5cos(x)’);
Characters, Strings, Texts
• Enclosing text in single quotes: >> S = 'I love MATLAB’
• To include a single quote inside astring, use two of them together:
>> SS = 'Green''s function’
• Displaying text on screen: >> disp([S ‘ ‘ SS]);
Logical Operators
>> L = sqrt(pi^3); >> L == 2 >> L ~= 2 >> L > 2 >> L >= 2 >> L < 2 >> L <= 2
if … then … else … end
>> a = pi^exp(1); c = exp(pi);>> if a >= c b = sqrt(a^2 - c^2) elseif a^c > c^a b = c^a/a^c else b = a^c/c^a end
Loops
• For loop: >> x = -1:.05:1; figure; >> for n = 1:8 subplot(4,2,n), plot(x,sin(n*pi*x)) end
• While loop: >> x = -1:.05:1; figure; n = 1; >> while n <= 8 subplot(4,2,n), plot(x,sin(n*pi*x)) n = n + 1; end
Script Files
• Click on toolbar to create new m-file• or select File | New | M-File on the menu• Saving series of commands into file
“m_sample.m”• Executing those commands by >> m_sample
Function m-files
function [A] = area(a,b,c)% Compute the area of a triangle whose% sides have length a, b and c.% Inputs: a,b,c: Lengths of sides% Output: A: area of triangle% Usage: Area = area(2,3,4);s = (a+b+c)/2;A = sqrt(s*(s-a)*(s-b)*(s-c));%%%%%%%%% end of area %%%%%%%%%%%
Projectile Motion of a Stone
If a stone is thrown vertically upward with an initial speed u = 60 m/s, its vertical displacement s after a time t has elapsed is given by the formula
s = ut −gt2/2,
where g is the acceleration due to gravity.
Air resistance has been ignored.
We would like to compute the value ofcompute the value of ss over a period of about 12.3 seconds at intervals of 0.1 seconds, and to plot the distanceplot the distance––time graph over this periodtime graph over this period
Projectile Motion of a Stone
Projectile Motion of a Stone
Master Plan:
1. Assign the data (g, u and t) to MATLAB variables.
2. Calculate the value of s according to the formula s = ut −gt2/2.
3. Plot the graph of s against t.
JugglingShow me the projectilemotion graph of threethree balls I’m juggling.
Only vertical motion is alright!
Try fivefive if you dare.
Simulink
• Integrated into MATLAB environment• Used for modeling and simulating
systems• Starting simulink by
– Click at the toolbar– Type at command line>> simulink
Example: Train System
• Represented by– two masses (M1 and M2)– connected together by a spring with stiffness
coefficient (k)– forces applied by the engine (F)– rolling friction coefficient (u)
Free Body Diagram
Constructing a Model• Click from “Simulink Library Browser” to open a new model window
Constructing a Model
• Drag AddAdd block from “Math Operations” sectionin Simulink Library Browser
• Drop it in model window
• Create 2 copies (one for each mass)
• Label them as “Sum_F1Sum_F1” and “Sum_F2Sum_F2”
Constructing a Model
• Drag 2 GainGain blocks into your model
• Attach each one with a line to the outputs ofthe AddAdd blocks
• Double-click on each GainGain block and enter“1/M1” and “1/M2” into each Gain field
• Label GainGain blocks as “a1” and “a2”
Constructing a Model
• Drag 2 IntegratorIntegrator blocks (from“Commonly Used Blocks”) into yourmodel for each of the accelerations
• Connect them with lines in two chains
• Label these integrators “v1”, “x1”, “v2”,and "x2"
Constructing a Model
• Drag 2 ScopeScope blocks from the “Sinks”library into your model
• Connect them to the outputs ofintegrators
• Label them “View_x1” and “View_x2”.
Constructing a Model
• Drag a Signal GeneratorSignal Generator block fromthe “Sources” library
• Connect it to the uppermost input of theSum_F1 block
• Label the Signal Generator “F”
Constructing a Model• Add another GainGain block into your model
• Set Gain field as u*g*M1
• Connect the input of GainGain block with link between v1and x1
• Connect the output with to Sum_F1
• Label GainGain block as “Friction_1”
Constructing a Model• Double-click to change the sign of Sum_F1 to “+--”
• Add a SubtractSubtract block below the rest of your model
• Label it as “(x1-x2)” and change its list of signs to “-+”
• Flip the block by right-click and select “Format | FlipBlock”
• Connect to “x1” and “x2”
Constructing a Model
• Drag a GainGain block into your model to the leftof Sum_F1
• Change it's value to “k” and label it “Spring”
• Connect the output of (x1-x2) to the input ofSpring
• Connect the output of Spring to the third inputof Sum_F1
Constructing a Model
• Tap off the output of Spring andconnect it to the first input of Sum_F2
• Add “Friction_2” and connect it to thesecond input of Sum_F2
• Change the signs of Sum_F2 to “+-”
Constructing a Model
• Add Scope blocks to view velocities andlabel them as “View_v1” and “View_v2”
• Double-click F to set– Waveform : square– Amplitude : -1– Frequency : 0.001
Model Parameter Settings
• Create an new m-file and enter thefollowing commands:
M1=1; M2=0.5;k=1; F=1; u=0.002; g=9.8;
• Execute your m-file to define thesevalues so that simulink can recognizethe variables.
Simulation
• Select Parameters from the Simulationmenu and change the Stop Time fieldto 1000
• Run the simulation and open thescopes to examine the output (selectautoscale in the right-click menu to seethe whole results)
Acknowledgement
• David F. Griffiths, “An Introduction to Matlab”,University of Dundee, 2005
• Timothy A. Davis and Kermit Sigmon, MATLAB®
Primer, Seventh Edition, Chapman & Hall/CRC, 2005
• Brian D. Hahn and Daniel T. Valentine, EssentialMATLAB® for Engineers and Scientists, Third Edition,Elsevier, 2007