Programming |
M-File Scripts and Functions
This section covers the following topics regarding functions:
M-File Scripts
Scripts are the simplest kind of M-file because they have no input or output arguments. They are useful for automating series of MATLAB commands, such as computations that you have to perform repeatedly from the command line.
The Base Workspace
Scripts share the base workspace with your interactive MATLAB session and with other scripts. They operate on existing data in the workspace, or they can create new data on which to operate. Any variables that scripts create remain in the workspace after the script finishes so you can use them for further computations. You should be aware, though, that running a script can unintentionally overwrite data stored in the base workspace by commands entered at the MATLAB command prompt.
Simple Script Example
These statements calculate rho
for several trigonometric functions of theta
, then create a series of polar plots:
% An M-file script to produce % Comment lines % "flower petal" plots theta = -pi:0.01:pi; % Computations rho(1,:) = 2*
sin(5*
theta) .^ 2; rho(2,:) = cos(10*
theta) .^ 3; rho(3,:) = sin(theta) .^ 2; rho(4,:) = 5*
cos(3.5*
theta) .^ 3; for k = 1:4 polar(theta, rho(k,:)) % Graphics output pause end
Try entering these commands in an M-file called petals.m
. This file is now a MATLAB script. Typing petals
at the MATLAB command line executes the statements in the script.
After the script displays a plot, press Enter or Return to move to the next plot. There are no input or output arguments; petals
creates the variables it needs in the MATLAB workspace. When execution completes, the variables (i
, theta
, and rho
) remain in the workspace. To see a listing of them, enter whos
at the command prompt.
Creating P-Code Files | M-File Functions |
© 1994-2005 The MathWorks, Inc.