Matlab+Programming+%28ang%29(1).pdf

(158 KB) Pobierz
Matlab Programming
Gerald W. Recktenwald
Department of Mechanical Engineering
Portland State University
gerry@me.pdx.edu
These slides are a supplement to the book Numerical Methods with
Matlab
: Implementations and Applications , by Gerald W. Recktenwald,
2001, Prentice-Hall, Upper Saddle River, NJ. These slides are c
2001 Gerald W. Recktenwald. The PDF version of these slides may
be downloaded or stored or printed only for noncommercial, educational
use. The repackaging or sale of these slides in any form, without written
consent of the author, is prohibited.
c
The latest version of this PDF file, along with other supplemental material
for the book, can be found at www.prenhall.com/recktenwald .
Version 0.97
August 28, 2001
Overview
Script m-files
Creating
Side effects
Function m-files
Syntax of I/O parameters
Text output
Primary and secondary functions
Flow control
Relational operators
Conditional execution of blocks
Loops
Vectorization
Using vector operations instead of loops
Preallocation of vectors and matrices
Logical and array indexing
Programming tricks
Variable number of I/O parameters
Indirect function evaluation
Inline function objects
Global variables
NMM:
Matlab
Programming
page 1
Preliminaries
Programs are contained in m-files
Plain text files – not binary files produced by word
processors
File must have “.m” extension
m-file must be in the path
Matlab maintains its own internal path
The path is the list of directories that Matlab will search
when looking for an m-file to execute.
A program can exist, and be free of errors, but it will not
run if
Matlab
cannot find it.
Manually modify the path with the path , addpath , and
rmpath built-in functions, or with addpwd NMM toolbox
function
. . . or use interactive Path Browser
NMM:
Matlab
Programming
page 2
Script Files
Not really programs
No input/output parameters
Script variables are part of workspace
Useful for tasks that never change
Useful as a tool for documenting homework:
Write a function that solves the problem for arbitrary
parameters
Use a script to run function for specific parameters
required by the assignment
Free Advice: Scripts offer no advantage over functions.
Functions have many advantages over scripts.
Always use functions instead of scripts.
NMM:
Matlab
Programming
page 3
Script to Plot tan( θ )
( 1 )
Enter statements in file called tanplot.m
1. Choose New. . . from File menu
2. Enter lines listed below
Contents of tanplot.m :
theta = linspace(1.6,4.6);
tandata = tan(theta);
plot(theta,tandata);
xlabel(’\theta (radians)’);
ylabel(’tan(\theta)’);
grid on;
axis([min(theta) max(theta) -5 5]);
3. Choose Save. . . from File menu
Save as tanplot.m
4. Run it
>> tanplot
NMM:
Matlab
Programming
page 4
935757551.001.png 935757551.002.png 935757551.003.png 935757551.004.png
 
Zgłoś jeśli naruszono regulamin