meam 211 university of pennsylvania 1 a matlab primer for meam 211 students jan 12, 2007

31
MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

Post on 15-Jan-2016

219 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

1

A Matlab Primer for MEAM 211 students

Jan 12, 2007

Page 2: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

2

Matlab Windows

The MATLAB command window displays a prompt (>>) at which expressions can be typed to invoke a computation. On different computers the window’s appearance may differ.

directory

History of commands that have been entered

Variables in memory

Page 3: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

3

Directory

Working directory on your laptop or in your eniac account on a CETS computer

To access the files in your working directory, you’ll want to change the pathname to:c:/Documents and Settings\Vijay Kumar\My Documents\matlabFiles.

Matlab working directory

Page 4: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

4

Scientific Calculator

Multiplication>> y=0.1*piy = 0.3142

Use of functions>> x=0.7x = 0.7000>> z=exp(x)*sin(y)z =

0.6223

Notation>> format long>> zz = 0.62228380907694>> format short e>> zz = 6.2228 e-01

Page 5: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

5

Dimensions and arrays

Row vector:

Column vector:

>> A = [0 1 2 3 5]

Matrix with m rows and n columns

>> A = [0; 1; 2; 3; 5]

>> A = [0 1 2 3 5]’

or

>> A = [0 1; 2 3; 5 7]

Page 6: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

6

Operations on matrices

Scalar addition, multiplication

Element by element multiplication

>> alpha = 1>> alpha + A

>> B = [0 1; 2 3; 4 5]>> A.*B

Page 7: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

7

Plotting functionsPlots of sin(3x), and exp(-2x)*sin(3x) from single command on matlab command line

>> x = 0:0.01:5;>> y = sin(3*x);>> plot(x,y)

Page 8: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

8

Example

Calculate the time at which projectile reaches the peak>> g=9.81; v_init=4; y_init=0; v_peak=0; t_peak=(v_init-v_peak)/g

t_peak =

1.0194

Calculate height at this time>> height_of_peak=v_init*t_peak - 1/2*g*t_peak^2

height_of_peak =

5.0968

Total time>> Total_time = 2*t_peak

Total_time =

2.0387

Calculate the height reached by a projectile thrown vertically with a 4 m/sec upward velocity?

Page 9: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

9

Plot Height and Velocity of Projectile over Timet=0:0.005:Total_time; % define an array of time points spanning the history

v=v_init-g*t; % evaluate velocities

y=v_init*t - 1/2 * g * t.^2; % evaluate positions (note the use of .^ instead of ^)

figure(1); plot(t, y); xlabel('Time (seconds)'); ylabel('Height (meters)');

figure(2); plot(t, v); ylabel('Time (seconds)'); ylabel('Velocity (meters/second)');

Page 10: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

10

Relational operatorsTraditional Notation

Infix Operator g

Infix Operator height_of_peak

Meaning Functional Operator

= g == 9.81 Height_of_peak == 1.2 equality eq

g ~= 9.81 Height_of_peak ~= 1.2 inequality ne

< g < 9.81 Height_of_peak < 1.2 less than lt

> g >= 9.81 Height_of_peak >= 1.2 greater than gt

< g <= 9.81 Height_of_peak <= 1.2 greater than or equal

ge

> g >= 9.81 Height_of_peak >= 1.2 less than or equal

le

Page 11: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

11

Relational OperatorsIs there any point in the trajectory that the height is < 0? Is the height always < 10 m?

>> any(y<0)

ans =

0>> all(y<10)

ans =

1

Is there any time at which the magnitude of the velocity exceeds (a) 5 m/s? (b) 10 m/s? Are all speeds greater than 5 m/s?

>> any(abs(v)>10)

ans =

0

>> any(abs(v)>5)

ans =

1

>> all(abs(v)>5)

ans =

0

Page 12: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

12

Logical operators

[Kaplan]

Page 13: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

13

Scripts or m-files

A SCRIPT file is an external file that contains a sequence

of MATLAB statements. By typing the filename, subsequent

MATLAB input is obtained from the file. SCRIPT files have

a filename extension of ".m" and are often called "M-files".

You can also use SCRIPT files to create your own functions.

Page 14: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

14

How to create m-files? M-files can be created in any text editor and saved with a filetype extension of .m as a text file (caution: no rtf or doc format!)

projectile.m created in WordPad on a PC projectile.m created with the Matlab editor on an Apple computer

Page 15: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

15

Script file for projectile calculations

g=9.81; % acceleration due to gravity = 9.81 m/sec^2v_init=10; % 10 meters/secondy_init=0; % initial position = 0 metersv_peak=0; % velocity at the highest positiont_peak=v_init/g; % time at which peak is achievedheight_of_peak=v_init*t_peak - 1/2*g*t_peak^2; % calculate height at time t=t_peak % plotting of trajectory Total_time = 2*t_peak; t=0:0.005:Total_time; % define an array of time points spanning the historyv=v_init-g*t; % evaluate velocitiesy=v_init*t - 1/2 * g * t.^2; % evaluate positions (note the use of .^ instead of ^) figure(1); plot(t, y); xlabel('Time (seconds)'); ylabel('Height (meters)'); figure(2); plot(t, v); ylabel('Time (seconds)'); ylabel('Velocity (meters/second)');

Click on File New M-FileCut and paste the text below into the body of the M-File.Click on File Save as “projectile.m”Type in the command prompt: >> projectile

Page 16: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

16

Creating functions

New functions may be added to MATLAB's vocabulary if they are expressed in terms of other existing functions. The commands and functions that comprise the new function must be put in a file whose name defines the name of the new function, with a filename extension of '.m'. At the top of the file must be a line that contains the syntax definition for the new function. For example, the existence of a file on disk called projectile.m with: function [x_final, xvelocity_final, yvelocity_final] = ... projectile(x_init, y_init, angle, speed)

%Projectile calculates the x coordinate (and the velocity) when the % projectile crosses the y=0 line

defines a new function called projectile that calculates the x coordinate (and the velocity) when the projectile crosses the y=0 line. The variables within the body of the function are all local variables.

Page 17: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

17

Function syntaxfunction res = ____________(_______________)

% _________________

res = ___________________________________;

function name arguments

description

expression using the arguments

function res = mathfun(x)% returns the result of a linear function with a slope of 5 and intercept of 10res = 5*x + 10;

First:Click on File New M-FileCut and paste the text above into the body of the M-File.Click on File Save as “mathfun.m”Try typing in the command prompt:

Intercept = 10

slope = 5

>> mathfun(0)

>> mathfun(1)

>> plot(mathfun([0:0.1:10]))

Page 18: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

18

Conditionals: The if statement

The conditional: A boolean expression that will always be evaluated and will return a scalar boolean 0 or 1

The YES block: An expression or set of expressions that will be evaluated only if the conditional expression returned 1

The NO block: Another expression or set of expressions that will be evaluated only if the conditional expression returned 0

if x < 0 res = -xelse res = xend

The YES block

The No block

The test condition

Page 19: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

19

When semi-colons?

What if we did not have a semi-colon after x?

if x < 0 res = -x;else res = x;end

Page 20: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

20

Loops

Why? Because you never want to repeat yourself

Quotation – the act of repeating erroneously the words of another (Ambrose Bierce)

Page 21: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

21

Example: Find the smallest number

% find the smallest number in a vector L

% initialize S to the first number in the listS = L(1);

for k = 2:length(L) if L(k) < X % we found a smaller number S = L(k); % so update S endend

Page 22: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

22

Homework Problem

Generate the column vector t

Generate the column vector v

Write a for loop to calculate the elements of the vector x

Page 23: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

23

A Matlab Primer for MEAM 211 studentsPart II

Jan 19, 2007

Page 24: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

24

Events and user interfaces

Page 25: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

25

Creating menus>> items={'A', 'B', 'C', 'D', 'Exit'}

items =

'A' 'B' 'C' 'D' 'Exit'

>> menu('What next?', items)

Getting input from keys

>> questdlg('Does this make sense?', 'A question for you')

Page 26: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

26

>> questdlg('Does this make sense?', 'A question for you')

Page 27: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

27

>> items={'A (integer)', 'B(real)', 'Exit(y/n)'}

items =

'A (integer)' 'B(real)' 'Exit(y/n)'

>> a=inputdlg(items, 'enter data')

a =

'1' '2.0' 'n'

Page 28: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

28

The graphical debugger

The dot at line 6 indicates that a breakpoint has been set there.

Open your projectile script created earlier:

>> edit projectile.m

Click somewhere in the body of the script file e.g. on line 6 height_of_peak=v_init*t_peak -...

In the editor window click Debug Set/Clear Breakpoint

Then type in the command window:

>> projectile

The arrow shows which line will next be evaluated. The arrow moves in the course of execution.

You can watch your variables as you step through the program in the Workspace

Page 29: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

29

Functions revisitedfunction res = ____________(_______________)

% _________________

res = ___________________________________;

function name arguments

description

expression using the arguments

function res = mathfun(x)% returns the result of a linear function with a slope of 5 and intercept of 10res = 5*x + 10;

First:Click on File New M-FileCut and paste the text above into the body of the M-File.Click on File Save as “mathfun.m”Try typing in the command prompt:

Intercept = 10

slope = 5

>> mathfun(0)

>> mathfun(1)

>> plot(mathfun([0:0.1:10]))

Page 30: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

30

Passing Functionsfunction funplot(f, lims)

% funplot(f, [left, right]) graph a function f(x)

% in the domain left <= x <= right

% A poor substitute for the built-in FPLOT

xpts = linspace(min(lims), max(lims), 100);

ypts = feval(f,xpts);

plot(xpts, ypts);

Here is funplot at work:>> funplot(@mathfun, [0 20])

Remember our ‘mathfun’ function:function res = mathfun(x)% returns the result of a function with a slope of 5 and an intercept of 10res = 5*x + 10;

Page 31: MEAM 211 University of Pennsylvania 1 A Matlab Primer for MEAM 211 students Jan 12, 2007

MEAM 211

University of Pennsylvania

31

Preparation for Project I

Represent the state of a mechanical system as a vector

Create function that calculates the derivative of the state vector

Learn to pass handles to functions

Write function that integrates for a fixed number of steps using the derivative function

Solve the kinematics problem and plot results