Upload
others
View
12
Download
0
Embed Size (px)
Citation preview
Outlines
Writing MATLAB Programs
Mike Renfro
September 14, 2004
Mike Renfro Writing MATLAB Programs
OutlinesPart I: Review of Previous LecturePart II: Writing MATLAB Programs
Review of Previous Lecture
Mike Renfro Writing MATLAB Programs
OutlinesPart I: Review of Previous LecturePart II: 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
Part I
Review of Previous Lecture
Mike Renfro Writing MATLAB Programs
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
Control StructuresWorking with Data and Graphics
Homework
Part II
Writing MATLAB Programs
Mike Renfro Writing MATLAB Programs
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
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
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 already used this type of logic in previous homeworkproblems. For example, on the bisection method, one of thesteps reads “if sgn(f (a)) = sgn(f (b)), stop, the program is setup wrong. Otherwise, continue on.”
Mike Renfro Writing MATLAB Programs
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
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: “loop 100000 times, adding 1.0/3.0 to resulteach time.”
Mike Renfro Writing MATLAB Programs
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;endfor n=1:100000
result=result -1.0/3.0;endfprintf(’result =%.15f\n’,result );
Mike Renfro Writing MATLAB Programs
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
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;endfprintf(’Found a root on the interval (%f,%f)\n’ ,...
x,x+dx);
Mike Renfro Writing MATLAB Programs
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
Control StructuresWorking with Data and Graphics
Homework
If/Then/ElseFor LoopsWhile LoopsVectorized Loops
Non-Vectorized Loop Example
clear allticfor n=1:100000
x(n)=log(n);endtoc
This code required 196 seconds to run on a Pentium 4 Xeon 2.8GHz system, and would probably require even more time on anormal PC.
Mike Renfro Writing MATLAB Programs
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 allticx=zeros (1 ,100000);for n=1:100000
x(n)=log(n);endtoc
This code required only 0.29 seconds to run on the same 2.8 GHzXeon system, required 0.40 seconds to run on a normal PC, andyields identical results compared to the first example.
Mike Renfro Writing MATLAB Programs
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 allticn=1:100000;x=log(n);toc
This version of the loop required only 0.02 seconds to run on theXeon, and only 0.05 seconds to run on a more typical PC.
Mike Renfro Writing MATLAB Programs
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:1999x(n)=(n*5)+5;y(n)=x(n)^2;
end
x=10:5:10000;y=x.^2;
Mike Renfro Writing MATLAB Programs
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
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:25x =
0 5 1015 20 25>> y=x^2??? Error using ==> ^Matrix must be square.>>
>> x=0:5:25x =
0 5 1015 20 25>> y=x.^2y =
0 25 100225 400 625>>
Mike Renfro Writing MATLAB Programs
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
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 Classparabola 1x11 88 double array
Grand total is 11 elements using 88 bytes>> parabolaparabola =
0 1 4 9 16 25 36 49 64 81 100>> y=parabola;
Mike Renfro Writing MATLAB Programs
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
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
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
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 Classx 1x11 88 double arrayy 1x11 88 double array
Grand total is 22 elements using 176 bytes
Mike Renfro Writing MATLAB Programs
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
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
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
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
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
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
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
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
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(v0 ,theta ,t);
Plot the (x , y) position of a projectile launched with the above v0
and θ parameters. Label the axes, title the graph, and place alegend on it.
Mike Renfro Writing MATLAB Programs