Beginners-1

Page 136

Other Programming Commands

117

function and an initial value and iterates the function a specified number of times: function final = iterate(func, init, num) final = init; for k = 1:num final = feval(func, final); end

Typing iterate(’cos’, 1, 2) yields the numerical value of cos(cos(1)), while iterate(’cos’, 1, 100) yields an approximation to the real number x for which cos(x) = x. (Think about it!) Most MATLAB commands that take a function name argument use feval, and as with all these commands, if you give the name of an inline function to feval, you should not enclose it in quotes.

Debugging In Chapter 3 we discussed some rudimentary debugging procedures. One suggestion was to insert the command keyboard into an M-file, for instance right before the line where an error occurs, so that you can examine the Workspace of the M-file at that point in its execution. A more effective and flexible way to do this kind of debugging is to use dbstop and related commands. With dbstop you can set a breakpoint in an M-file in a number of ways, for example, at a specific line number, or whenever an error occurs. Type help dbstop for a list of available options. When a breakpoint is reached, a prompt beginning with the letter K will appear in the Command Window, just as if keyboard were inserted in the M-file at the breakpoint. In addition, the location of the breakpoint is highlighted with an arrow in the Editor/Debugger (which is opened automatically if you were not already editing the M-file). At this point you can examine in the Command Window the variables used in the M-file, set another breakpoint with dbstop, clear breakpoints with dbclear, etc. If you are ready to continue running the M-file, type dbcont to continue or dbstep to step through the file line-by-line. You can also stop execution of the M-file and return immediately to the usual command prompt with dbquit.

☞ You can also perform all the command-line functions that we described in this section with the mouse and/or keyboard shortcuts in the Editor/Debugger. See the section Debugging Techniques in Chapter 11 for more about debugging commands and features of the Editor/Debugger.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.