writing matlab programs - ttu cae networkmwr/shortcourses/matlab/02 writing matlab...writing matlab...

36
Outlines Writing MATLAB Programs Mike Renfro September 10, 2004 Mike Renfro Writing MATLAB Programs

Upload: hoanghuong

Post on 23-Jun-2018

271 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Outlines

Writing MATLAB Programs

Mike Renfro

September 10, 2004

Mike Renfro Writing MATLAB Programs

Page 2: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

OutlinesPart I: Review of Previous LecturePart I: Writing MATLAB Programs

Review of Previous Lecture

Mike Renfro Writing MATLAB Programs

Page 3: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

OutlinesPart I: Review of Previous LecturePart I: Writing MATLAB Programs

Writing MATLAB Programs

Control StructuresIf/Then/ElseFor LoopsWhile LoopsVectorized Loops

Working with Data and GraphicsLoading and Saving Data with Text FilesLoading and Saving Data with MATLAB Binary FilesX-Y Plots

“Homework”

Mike Renfro Writing MATLAB Programs

Page 4: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Part I

Review of Previous Lecture

Mike Renfro Writing MATLAB Programs

Page 5: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Review of Previous Lecture

Starting MATLAB, exiting MATLAB, getting help

Major elements of the MATLAB environment

Command windowWorkspaceCommand historyCurrent directory selector

MATLAB as a calculator

Writing functions

Mike Renfro Writing MATLAB Programs

Page 6: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

Part II

Writing MATLAB Programs

Mike Renfro Writing MATLAB Programs

Page 7: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

Introduction

In their simplest form, MATLAB programs are like functionswithout the function header line. They are simple text files thatcontain several MATLAB commands to be run in a consistentfashion. For example:

% Calculate projectile positions at a given time

initialVelocity =5; % m/s

launchAngle =45*( pi /180); % radians

time =2; % seconds

[xPosition ,yPosition ]=...

computeprojectileposition(initialVelocity ,...

launchAngle ,time)

Mike Renfro Writing MATLAB Programs

Page 8: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

If/Then/ElseFor LoopsWhile LoopsVectorized Loops

Control Structures

Control structures are ways of making programs do somethingother than simply execute lines of the program in order. Controlstructures allow programs to make decisions, and to repeatcalculations while certain conditions are met.

Mike Renfro Writing MATLAB Programs

Page 9: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

If/Then/ElseFor LoopsWhile LoopsVectorized Loops

If/Then/Else Structures

If/Then/Else structures allow your program to make decisionsbased on calculations or other information.

Their general form is “if a condition is met, do this.Otherwise, do something else”.

You’ve probably already used this type of logic in previousproblems.

Mike Renfro Writing MATLAB Programs

Page 10: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

If/Then/ElseFor LoopsWhile LoopsVectorized Loops

MATLAB If/Then/Else Example

width =0;

height =5;

depth =3;

density =10;

volume=width*height*depth;

if (volume <=0)

error(’How did I get a non -positive volume?’);

else

weight=density*volume;

end

Mike Renfro Writing MATLAB Programs

Page 11: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

If/Then/ElseFor LoopsWhile LoopsVectorized Loops

For Loops

For loops are used when you want to repeat a calculation a specificnumber of times. Your first programming assignment used aconstruct like that.

Mike Renfro Writing MATLAB Programs

Page 12: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

If/Then/ElseFor LoopsWhile LoopsVectorized Loops

For Loop Example

result =9;

for n=1:100000

result=result +1.0/3.0;

end

for n=1:100000

result=result -1.0/3.0;

end

fprintf(’result =%.15f\n’,result );

Mike Renfro Writing MATLAB Programs

Page 13: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

If/Then/ElseFor LoopsWhile LoopsVectorized Loops

While Loops

While loops are used when you want to repeat a calculation until aparticular criteria is met. Normally, you don’t know exactly howmany loops will be required to meet that criteria beforehand. Theincremental search method used constructs like that: “repeat theprevious steps as long as sgn(f (x)) = sgn(f (x + ∆x))”.

Mike Renfro Writing MATLAB Programs

Page 14: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

If/Then/ElseFor LoopsWhile LoopsVectorized Loops

While Loop Example

x=0;

dx=0.1;

while (sign(myfunction(x)) == sign(myfunction(x+dx)))

x=x+dx;

end

fprintf(’Found a root on the interval (%f,%f)\n’ ,...

x,x+dx);

Mike Renfro Writing MATLAB Programs

Page 15: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

If/Then/ElseFor LoopsWhile LoopsVectorized Loops

Vectorized Loops

One of MATLAB’s advantages over other languages is that itdoes not require you to predefine every variable with a typeand a size before using it. You can add extra elements to anarray or vector anytime during the variable’s lifetime.

However, this flexibility comes at a price. When MATLAB hasto resize an array, it has to

find new memory for the larger array,allocate that memory,copy the existing array into the new memory location,and add the new array element onto the end.

All these operations add on to your total time required tosolve a problem. When you repeat this operation tens orhundreds of thousands of times, it can really slow things down.

Mike Renfro Writing MATLAB Programs

Page 16: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

If/Then/ElseFor LoopsWhile LoopsVectorized Loops

Non-Vectorized Loop Example

clear all

tic

for n=1:100000

x(n)=log(n);

end

toc

This code required 38 seconds to run on a AMD Opteron 2.8 GHzsystem, and 23 seconds on a Core2 Duo Laptop.

Mike Renfro Writing MATLAB Programs

Page 17: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

If/Then/ElseFor LoopsWhile LoopsVectorized Loops

Better Non-Vectorized Loop Example

How much difference would it make if we preallocated the memoryfor the ‘x’ variable rather than resizing it on each run through theloop?

clear all

tic

x=zeros (1 ,100000);

for n=1:100000

x(n)=log(n);

end

toc

This code required only 0.009 seconds to run on the Opteronsystem, required 0.23 seconds to run on the laptop, and yieldsidentical results compared to the first example.

Mike Renfro Writing MATLAB Programs

Page 18: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

If/Then/ElseFor LoopsWhile LoopsVectorized Loops

Vectorized Loop Example

What’s the code for and the effect of a vectorized loop?

clear all

tic

n=1:100000;

x=log(n);

toc

This version of the loop required only 0.006 seconds to run on theOpteron, and only 0.012 seconds to run on the laptop.

Mike Renfro Writing MATLAB Programs

Page 19: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

If/Then/ElseFor LoopsWhile LoopsVectorized Loops

Other Vectorized Examples

n=1;

while (n <=1999)

x(n)=(n*5)+5;

y(n)=x(n)^2;

n=n+1;

end

for n=1:1999

x(n)=(n*5)+5;

y(n)=x(n)^2;

end

x=10:5:10000;

y=x.^2;

Mike Renfro Writing MATLAB Programs

Page 20: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

If/Then/ElseFor LoopsWhile LoopsVectorized Loops

Vectorized Loop Warning

Since vectors in MATLAB are actually single-row or single-columnmatrices, MATLAB treats them according to the rules of matrixalgebra.The most common problem with vector calculations are withmultiplication or division operations, since matrix algebra rulesrequire that matrices multiplied or divided together must be of aparticular size. Plus, the required sizes almost never show up invectorized loops.

Mike Renfro Writing MATLAB Programs

Page 21: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

If/Then/ElseFor LoopsWhile LoopsVectorized Loops

Vectorized Loop Solution

Put a period before any multiplication, division, or power symbol ina vectorized calculation:

>> x=0:5:25

x =

0 5 10

15 20 25

>> y=x^2

??? Error using ==> ^

Matrix must be square.

>>

>> x=0:5:25

x =

0 5 10

15 20 25

>> y=x.^2

y =

0 25 100

225 400 625

>>

Mike Renfro Writing MATLAB Programs

Page 22: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

Loading and Saving Data with Text FilesLoading and Saving Data with MATLAB Binary FilesX-Y Plots

Saving Data to a Text File

If you need to save the results of some MATLAB calculations toavoid the need to repeat the same calculations over and over, youcan save any MATLAB variable into a text file:

>> x=0:10;

>> y=x.^2;

>> save -ascii parabola.txt y

Mike Renfro Writing MATLAB Programs

Page 23: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

Loading and Saving Data with Text FilesLoading and Saving Data with MATLAB Binary FilesX-Y Plots

Loading Data from a Text File

Similarly, you can load previously-calculated results from a text file.It doesn’t matter whether the text file contains results fromMATLAB or from another program, as long as it’s formattedproperly:

>> clear all

>> load -ascii parabola.txt

>> whos

Name Size Bytes Class

parabola 1x11 88 double array

Grand total is 11 elements using 88 bytes

>> parabola

parabola =

0 1 4 9 16 25 36 49 64 81 100

>> y=parabola;

Mike Renfro Writing MATLAB Programs

Page 24: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

Loading and Saving Data with Text FilesLoading and Saving Data with MATLAB Binary FilesX-Y Plots

Text File Advantages

Very easy to exchange data between MATLAB and otherapplications, such as Excel, LabVIEW, Tecplot, etc.

Very easy to exchange data between MATLAB and custom C,C++, or FORTRAN programs.

Data can be examined, created, or modified with a text editorsuch as Notepad.

Mike Renfro Writing MATLAB Programs

Page 25: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

Loading and Saving Data with Text FilesLoading and Saving Data with MATLAB Binary FilesX-Y Plots

Text File Disadvantages

Only one variable may be stored per text file.

Only 8 digits of precision are stored in the text file.

Slow performance on loading or saving very large data sets.

Mike Renfro Writing MATLAB Programs

Page 26: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

Loading and Saving Data with Text FilesLoading and Saving Data with MATLAB Binary FilesX-Y Plots

Saving Data to a MATLAB Binary File

>> x=0:10;

>> y=x.^2;

>> save parabola.mat

Mike Renfro Writing MATLAB Programs

Page 27: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

Loading and Saving Data with Text FilesLoading and Saving Data with MATLAB Binary FilesX-Y Plots

Loading Data from a MATLAB Binary File

>> clear all

>> load parabola

>> whos

Name Size Bytes Class

x 1x11 88 double array

y 1x11 88 double array

Grand total is 22 elements using 176 bytes

Mike Renfro Writing MATLAB Programs

Page 28: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

Loading and Saving Data with Text FilesLoading and Saving Data with MATLAB Binary FilesX-Y Plots

MATLAB Binary File Advantages

Multiple variables may be stored in a single .mat file, even theentire MATLAB workspace.

No precision is lost in the transfer. Variables are not truncatedat the eighth decimal place.

Fast performance on loading or saving very large data sets.

Mike Renfro Writing MATLAB Programs

Page 29: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

Loading and Saving Data with Text FilesLoading and Saving Data with MATLAB Binary FilesX-Y Plots

MATLAB Binary File Disadvantages

More difficult to exchange data between MATLAB and otherapplications, such as Excel, LabVIEW, Tecplot, etc.

More difficult to exchange data between MATLAB andcustom C, C++, or FORTRAN programs.

Mike Renfro Writing MATLAB Programs

Page 30: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

Loading and Saving Data with Text FilesLoading and Saving Data with MATLAB Binary FilesX-Y Plots

Basic X-Y Plots

Assuming you already have a set of x and y data (or x and t data,etc.), the plot command can plot them against each other.

>> t=0:0.01:1;

>> x=exp(-t).* sin (5*pi*t);

>> plot(t,x)

Mike Renfro Writing MATLAB Programs

Page 31: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

Loading and Saving Data with Text FilesLoading and Saving Data with MATLAB Binary FilesX-Y Plots

X-Y Plot Result

Mike Renfro Writing MATLAB Programs

Page 32: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

Loading and Saving Data with Text FilesLoading and Saving Data with MATLAB Binary FilesX-Y Plots

Multiple Traces on One Graph

>> t=0:0.01:1;

>> x=exp(-t).* sin (5*pi*t);

>> plot(t,x)

>> x2=exp(-2*t).* sin (4*pi*t);

>> plot(t,x,t,x2)

Mike Renfro Writing MATLAB Programs

Page 33: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

Loading and Saving Data with Text FilesLoading and Saving Data with MATLAB Binary FilesX-Y Plots

X-Y Plot Result

Mike Renfro Writing MATLAB Programs

Page 34: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

Loading and Saving Data with Text FilesLoading and Saving Data with MATLAB Binary FilesX-Y Plots

Graph Labels, Titles, and Legends

>> t=0:0.01:1;

>> x=exp(-t).* sin (5*pi*t);

>> plot(t,x)

>> x2=exp(-2*t).* sin (4*pi*t);

>> plot(t,x,t,x2)

>> xlabel(’Time (s)’);

>> ylabel(’Displacement (mm)’);

>> title(’Motion Observed at Tip of Beam’);

>> legend(’Beam 1’,’Beam 2’);

Mike Renfro Writing MATLAB Programs

Page 35: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

Loading and Saving Data with Text FilesLoading and Saving Data with MATLAB Binary FilesX-Y Plots

X-Y Plot Result

Mike Renfro Writing MATLAB Programs

Page 36: Writing MATLAB Programs - TTU CAE Networkmwr/shortcourses/matlab/02 Writing MATLAB...Writing MATLAB Programs Mike Renfro September 10, ... and 23 seconds on a Core2 Duo Laptop

Control StructuresWorking with Data and Graphics

“Homework”

“Homework”

Update your projectile motion calculators to accept a vector oftimes, rather than a single value. For example, the following codeshould calculate a series of (x , y) values:

>> v0=5;

>> theta=pi/4;

>> t=0:0.01:1;

>> [x,y]= computeprojectileposition(x0 ,y0 ,v0 ,...

theta ,t);

Plot the (x , y) position of a projectile launched with the above v0and θ parameters—pick your own (x0,y0). Label the axes, title thegraph, and place a legend on it.

Mike Renfro Writing MATLAB Programs