23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

4 M-File <strong>Programming</strong><br />

Saving the Program<br />

It is usually a good idea to save your program periodically while you are in the<br />

development process. To do this, click File > Save in the Editor/Debugger.<br />

Enter a filename with a .m extension in the Save file as dialog box that<br />

appears and click OK. It is customary and less confusing if you give the M-file<br />

the same name as the first function in the M-file.<br />

Running the Program<br />

Before trying to run your program, make sure that its M-file is on the<br />

<strong>MATLAB</strong> path. The <strong>MATLAB</strong> path defines those directories that you want<br />

<strong>MATLAB</strong> to know about when executing M-files. The path includes all the<br />

directories that contain functions provided with <strong>MATLAB</strong>. It should also<br />

include any directories that you use for your own functions.<br />

Use the which function to see if your program is on the path:<br />

which drawPlot<br />

D:\matlabR14\work\drawPlot.m<br />

If not, add its directory to the path using the addpath function:<br />

addpath('D:\matlabR14\work')<br />

Now you can run the program just by typing the name of the M-file at the<br />

<strong>MATLAB</strong> command prompt:<br />

drawPlot(xdata, ydata)<br />

Getting the Bugs Out<br />

In all but the simplest programs, you are likely to encounter some type of<br />

unexpected behavior when you run the program for the first time. Program<br />

defects can show up in the form of warning or error messages displayed in the<br />

command window, programs that hang (never terminate), inaccurate results,<br />

or some number of other symptoms. This is where the second functionality<br />

of the <strong>MATLAB</strong> Editor/Debugger becomes useful.<br />

The <strong>MATLAB</strong> Debugger enables you to examine the inner workings of your<br />

program while you run it. You can stop the execution of your program at any<br />

point and then continue from that point, stepping through the code line by<br />

4-4

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!