Sunteți pe pagina 1din 36

Outlines

Writing MATLAB Programs


Mike Renfro September 14, 2004

Mike Renfro

Writing MATLAB Programs

Outlines

Part I: Review of Previous Lecture Part II: Writing MATLAB Programs

Review of Previous Lecture

Mike Renfro

Writing MATLAB Programs

Outlines

Part I: Review of Previous Lecture Part II: Writing MATLAB Programs

Writing MATLAB Programs


Control Structures
If/Then/Else For Loops While Loops Vectorized Loops

Working with Data and Graphics


Loading and Saving Data with Text Files Loading and Saving Data with MATLAB Binary Files X-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 window Workspace Command history Current directory selector

MATLAB as a calculator Writing functions

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

Part II Writing MATLAB Programs

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

Introduction
In their simplest form, MATLAB programs are like functions without the function header line. They are simple text les that contain several MATLAB commands to be run in a consistent fashion. For example:
% Calculate projectile positions at a given time initialVelocity =5; % m / s launchAngle =45*( pi /180); % radians time =2; % seconds [ xPosition , yPosition ]=... c o m p u t e p r o j e c t i l e p o s i t i o n ( initialVelocity ,... launchAngle , time )

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

If/Then/Else For Loops While Loops Vectorized Loops

Control Structures

Control structures are ways of making programs do something other than simply execute lines of the program in order. Control structures allow programs to make decisions, and to repeat calculations while certain conditions are met.

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

If/Then/Else For Loops While Loops Vectorized Loops

If/Then/Else Structures

If/Then/Else structures allow your program to make decisions based on calculations or other information. Their general form is if a condition is met, do this. Otherwise, do something else. Youve already used this type of logic in previous homework problems. For example, on the bisection method, one of the steps reads if sgn(f (a)) = sgn(f (b )), stop, the program is set up wrong. Otherwise, continue on.

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

If/Then/Else For Loops While Loops Vectorized 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 Structures Working with Data and Graphics Homework

If/Then/Else For Loops While Loops Vectorized Loops

For Loops

For loops are used when you want to repeat a calculation a specic number of times. Your rst programming assignment used a construct like that: loop 100000 times, adding 1.0/3.0 to result each time.

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

If/Then/Else For Loops While Loops Vectorized 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 =%.15 f \ n , result );

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

If/Then/Else For Loops While Loops Vectorized Loops

While Loops

While loops are used when you want to repeat a calculation until a particular criteria is met. Normally, you dont know exactly how many loops will be required to meet that criteria beforehand. The incremental search method used constructs like that: repeat the previous steps as long as sgn(f (x )) = sgn(f (x + x )).

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

If/Then/Else For Loops While Loops Vectorized 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

Control Structures Working with Data and Graphics Homework

If/Then/Else For Loops While Loops Vectorized Loops

Vectorized Loops
One of MATLABs advantages over other languages is that it does not require you to predene every variable with a type and a size before using it. You can add extra elements to an array or vector anytime during the variables lifetime. However, this exibility comes at a price. When MATLAB has to resize an array, it has to
nd 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 to solve a problem. When you repeat this operation tens or hundreds of thousands of times, it can really slow things down.
Mike Renfro Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

If/Then/Else For Loops While Loops Vectorized Loops

Non-Vectorized Loop Example

clear all tic for n =1:100000 x ( n )= log ( n ); end toc

This code required 196 seconds to run on a Pentium 4 Xeon 2.8 GHz system, and would probably require even more time on a normal PC.

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

If/Then/Else For Loops While Loops Vectorized Loops

Better Non-Vectorized Loop Example


How much dierence would it make if we preallocated the memory for the x variable rather than resizing it on each run through the loop?
clear all tic x = zeros (1 ,100000); for n =1:100000 x ( n )= log ( n ); end toc

This code required only 0.29 seconds to run on the same 2.8 GHz Xeon system, required 0.40 seconds to run on a normal PC, and yields identical results compared to the rst example.
Mike Renfro Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

If/Then/Else For Loops While Loops Vectorized Loops

Vectorized Loop Example

Whats the code for and the eect of a vectorized loop?


clear all tic n =1:100000; x = log ( n ); toc

This version of the loop required only 0.02 seconds to run on the Xeon, and only 0.05 seconds to run on a more typical PC.

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

If/Then/Else For Loops While Loops Vectorized 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

Control Structures Working with Data and Graphics Homework

If/Then/Else For Loops While Loops Vectorized Loops

Vectorized Loop Warning

Since vectors in MATLAB are actually single-row or single-column matrices, MATLAB treats them according to the rules of matrix algebra. The most common problem with vector calculations are with multiplication or division operations, since matrix algebra rules require that matrices multiplied or divided together must be of a particular size. Plus, the required sizes almost never show up in vectorized loops.

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

If/Then/Else For Loops While Loops Vectorized Loops

Vectorized Loop Solution


Put a period before any multiplication, division, or power symbol in a 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

Control Structures Working with Data and Graphics Homework

Loading and Saving Data with Text Files Loading and Saving Data with MATLAB Binary Files X-Y Plots

Saving Data to a Text File

If you need to save the results of some MATLAB calculations to avoid the need to repeat the same calculations over and over, you can save any MATLAB variable into a text le:
>> x =0:10; >> y = x .^2; >> save - ascii parabola . txt y

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

Loading and Saving Data with Text Files Loading and Saving Data with MATLAB Binary Files X-Y Plots

Loading Data from a Text File


Similarly, you can load previously-calculated results from a text le. It doesnt matter whether the text le contains results from MATLAB or from another program, as long as its formatted properly:
>> clear all >> load - ascii parabola . txt >> whos Name Size Bytes Class parabola 1 x11 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

Control Structures Working with Data and Graphics Homework

Loading and Saving Data with Text Files Loading and Saving Data with MATLAB Binary Files X-Y Plots

Text File Advantages

Very easy to exchange data between MATLAB and other applications, 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 modied with a text editor such as Notepad.

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

Loading and Saving Data with Text Files Loading and Saving Data with MATLAB Binary Files X-Y Plots

Text File Disadvantages

Only one variable may be stored per text le. Only 8 digits of precision are stored in the text le. Slow performance on loading or saving very large data sets.

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

Loading and Saving Data with Text Files Loading and Saving Data with MATLAB Binary Files X-Y Plots

Saving Data to a MATLAB Binary File

>> x =0:10; >> y = x .^2; >> save parabola . mat

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

Loading and Saving Data with Text Files Loading and Saving Data with MATLAB Binary Files X-Y Plots

Loading Data from a MATLAB Binary File

>> clear all >> load parabola >> whos Name Size Bytes Class x 1 x11 88 double array y 1 x11 88 double array Grand total is 22 elements using 176 bytes

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

Loading and Saving Data with Text Files Loading and Saving Data with MATLAB Binary Files X-Y Plots

MATLAB Binary File Advantages

Multiple variables may be stored in a single .mat le, even the entire MATLAB workspace. No precision is lost in the transfer. Variables are not truncated at the eighth decimal place. Fast performance on loading or saving very large data sets.

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

Loading and Saving Data with Text Files Loading and Saving Data with MATLAB Binary Files X-Y Plots

MATLAB Binary File Disadvantages

More dicult to exchange data between MATLAB and other applications, such as Excel, LabVIEW, Tecplot, etc. More dicult to exchange data between MATLAB and custom C, C++, or FORTRAN programs.

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

Loading and Saving Data with Text Files Loading and Saving Data with MATLAB Binary Files X-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 Structures Working with Data and Graphics Homework

Loading and Saving Data with Text Files Loading and Saving Data with MATLAB Binary Files X-Y Plots

X-Y Plot Result

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

Loading and Saving Data with Text Files Loading and Saving Data with MATLAB Binary Files X-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 Structures Working with Data and Graphics Homework

Loading and Saving Data with Text Files Loading and Saving Data with MATLAB Binary Files X-Y Plots

X-Y Plot Result

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

Loading and Saving Data with Text Files Loading and Saving Data with MATLAB Binary Files X-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 Structures Working with Data and Graphics Homework

Loading and Saving Data with Text Files Loading and Saving Data with MATLAB Binary Files X-Y Plots

X-Y Plot Result

Mike Renfro

Writing MATLAB Programs

Control Structures Working with Data and Graphics Homework

Homework
Update your projectile motion calculators to accept a vector of times, rather than a single value. For example, the following code should calculate a series of (x , y ) values:
>> >> >> >> v0 =5; theta = pi /4; t =0:0.01:1; [x , y ]= c o m p u t e p r o j e c t i l e p o s it i o n ( 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 a legend on it.

Mike Renfro

Writing MATLAB Programs

S-ar putea să vă placă și