56
Get Started with MATLAB and Simulink An Introductory Tutorial CPE111 Computer Engineering Exploration 2010 Dr.Boonserm Kaewkamnerdpong

Get Started With MATLAB 2010-Student Handout

Embed Size (px)

Citation preview

Page 1: Get Started With MATLAB 2010-Student Handout

Get Started with MATLABand Simulink

An Introductory Tutorial

CPE111 Computer Engineering Exploration2010

Dr.Boonserm Kaewkamnerdpong

Page 2: Get Started With MATLAB 2010-Student Handout

What is MATLAB?

• MAT + LAB … Matrix LaboratoryMatrix Laboratory

• Interactive system for doing numericalcomputations

• Powerful tool for calculations inscientific and engineering problems

Page 3: Get Started With MATLAB 2010-Student Handout

MATLAB Components

Command WindowCommand Window

Command HistoryCommand History

WorkspaceWorkspace

Page 4: Get Started With MATLAB 2010-Student Handout

MATLAB Components

Page 5: Get Started With MATLAB 2010-Student Handout

MATLAB as a Calculator

• Arithmetic: >> 2 + 3 >> 3 - 2 >> 2 * 3 >> 1 / 2 >> 2 ^ 3 >> 2 \ 1

Page 6: Get Started With MATLAB 2010-Student Handout

Numbers & Formats

• Integer ………………… 1362, -217897• Real …………………… -1.234, -10.76• Complex ……………… -3.21 - 4.3i• Infinity “Inf”• Not a number “NaN”

Page 7: Get Started With MATLAB 2010-Student Handout

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

Page 8: Get Started With MATLAB 2010-Student Handout

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

Page 9: Get Started With MATLAB 2010-Student Handout

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

Page 10: Get Started With MATLAB 2010-Student Handout

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

Page 11: Get Started With MATLAB 2010-Student Handout

• 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

Page 12: Get Started With MATLAB 2010-Student Handout

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

Page 13: Get Started With MATLAB 2010-Student Handout

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’

Page 14: Get Started With MATLAB 2010-Student Handout

Arithmetic of Vectors/Matrices

>> v + 3 ans =

>> v * 3 ans =

>> v * c ans =

What about What about ““c * vc * v””??

Page 15: Get Started With MATLAB 2010-Student Handout

>> c * v ans =

Arithmetic of Vectors/Matrices

>> c .* c ans =

Page 16: Get Started With MATLAB 2010-Student Handout

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

Page 17: Get Started With MATLAB 2010-Student Handout

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)’);

Page 18: Get Started With MATLAB 2010-Student Handout
Page 19: Get Started With MATLAB 2010-Student Handout

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

Page 20: Get Started With MATLAB 2010-Student Handout

Logical Operators

>> L = sqrt(pi^3); >> L == 2 >> L ~= 2 >> L > 2 >> L >= 2 >> L < 2 >> L <= 2

Page 21: Get Started With MATLAB 2010-Student Handout

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

Page 22: Get Started With MATLAB 2010-Student Handout

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

Page 23: Get Started With MATLAB 2010-Student Handout

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

Page 24: Get Started With MATLAB 2010-Student Handout

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 %%%%%%%%%%%

Page 25: Get Started With MATLAB 2010-Student Handout

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

Page 26: Get Started With MATLAB 2010-Student Handout

Projectile Motion of a Stone

Page 27: Get Started With MATLAB 2010-Student Handout

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.

Page 28: Get Started With MATLAB 2010-Student Handout

JugglingShow me the projectilemotion graph of threethree balls I’m juggling.

Only vertical motion is alright!

Try fivefive if you dare.

Page 29: Get Started With MATLAB 2010-Student Handout

Simulink

• Integrated into MATLAB environment• Used for modeling and simulating

systems• Starting simulink by

– Click at the toolbar– Type at command line>> simulink

Page 30: Get Started With MATLAB 2010-Student Handout
Page 31: Get Started With MATLAB 2010-Student Handout

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)

Page 32: Get Started With MATLAB 2010-Student Handout

Free Body Diagram

Page 33: Get Started With MATLAB 2010-Student Handout

Constructing a Model• Click from “Simulink Library Browser” to open a new model window

Page 34: Get Started With MATLAB 2010-Student Handout

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”

Page 35: Get Started With MATLAB 2010-Student Handout
Page 36: Get Started With MATLAB 2010-Student Handout

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”

Page 37: Get Started With MATLAB 2010-Student Handout
Page 38: Get Started With MATLAB 2010-Student Handout

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"

Page 39: Get Started With MATLAB 2010-Student Handout
Page 40: Get Started With MATLAB 2010-Student Handout

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

Page 41: Get Started With MATLAB 2010-Student Handout
Page 42: Get Started With MATLAB 2010-Student Handout

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”

Page 43: Get Started With MATLAB 2010-Student Handout

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”

Page 44: Get Started With MATLAB 2010-Student Handout
Page 45: Get Started With MATLAB 2010-Student Handout

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”

Page 46: Get Started With MATLAB 2010-Student Handout
Page 47: Get Started With MATLAB 2010-Student Handout

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

Page 48: Get Started With MATLAB 2010-Student Handout
Page 49: Get Started With MATLAB 2010-Student Handout

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 “+-”

Page 50: Get Started With MATLAB 2010-Student Handout
Page 51: Get Started With MATLAB 2010-Student Handout

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

Page 52: Get Started With MATLAB 2010-Student Handout
Page 53: Get Started With MATLAB 2010-Student Handout

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.

Page 54: Get Started With MATLAB 2010-Student Handout

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)

Page 55: Get Started With MATLAB 2010-Student Handout
Page 56: Get Started With MATLAB 2010-Student Handout

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