Files For An Example Session

Một phần của tài liệu Giáo trình Matlab: using matlab (Trang 85 - 99)

To try the Debugger, first create an M-file called variance.m that accepts an input vector and returns an unbiased variance estimate. This file calls another M-file, sqsum, that computes the mean-removed squared sum for the input vector.

function y = variance(x) mu = sum(x)/length(x);

tot = sqsum(x,mu);

y = tot/(length(x)–1);

Create the sqsum.m file exactly as it is shown below, complete with a planted bug.

function tot = sqsum(x,mu) tot = 0;

for i = 1:length(mu)

tot = tot + ((x(i)–mu).^2);

end

Note The example above is coded for illustrative purposes only. Whenever possible, avoid for loops and use vectorization for the most efficient execution.

Trial Run

Try out the M-files to see if they work correctly. Use MATLAB’s std function to compute results.

Create a test vector at the command line.

v = [1 2 3 4 5];

Compute the variance using std. var1 = std(v).^2

var1 = 2.5000

Now try the variance function from above.

myvar1 = variance(v) myvar1 =

1

The answer is wrong. Let’s use the Debugger to isolate the error in the M-files.

The following section shows a sample session using the Editor/Debugger graphical user interface, as well as one from the command line.

Debugging Using the Graphical User Interface

To start debugging:

If you have just created the M-files using the Editor/Debugger window, you can continue from this point.

If you’ve created the M-files using an external text editor, start the Editor/

Debugger and then click the Open M-file button on the toolbar.

MATLAB Debugger

The Editor/Debugger toolbar contains a series of debugging icons.

A right-button mouse click in the Editor window produces a pop-up menu of some of the options.

Setting Breakpoints

Most debugging sessions start by setting a breakpoint. Breakpoints stop M-file Toolbar

Button

Purpose Description Equivalent

Command Set/Clear Breakpoint Set or clear a

breakpoint at the line containing the cursor.

dbstop/

dbclear

Clear All Breakpoints Clear all breakpoints that are currently set.

dbclear all

Step In Execute the current

line of the M-file and, if the line is a call to another function, step into that function.

dbstep in

Single Step Execute the current line of the M-file.

dbstep

Continue Continue execution of M-file until

completion or until another breakpoint is encountered.

dbcont

Quit Debugging Exit the debugging state.

dbquit

function’s workspace before resuming execution. A breakpoint is set or cleared at the line containing the cursor. A red stop sign ( ) next to a line indicates that a breakpoint is set at that line. If the line selected for a breakpoint is not a valid executable line, then the breakpoint is set at the next executable line.

Note The Debugger’s Breakpoints menu also lets you halt M-file execution if your code generates a warning, error, or NaN or Inf value.

At the beginning of the debugging session, you’re not sure where the error in the variance function is, or even if it’s in the variance.m or sqsum.m file. A logical place to insert a breakpoint is after the computation of the mean and the mean-removed squared sum. Open variance.m and set a breakpoint at line 4.

y = tot/(length(x)–1);

The line number is indicated at the bottom right of the status bar. Set the breakpoint by positioning the cursor in the line of text and click on the breakpoint icon in the toolbar. Alternatively, you can choose Set Breakpoint from the Debug menu, or right-click to bring up the context menu and choose Set/Clear Breakpoint.

MATLAB Debugger

Examining Variables

To get to the breakpoint and check the values of interest, first execute the function from the Command Window.

variance(v)

When execution of an M-file pauses at a breakpoint, the yellow arrow to the left of the text ( ) shows the next line to execute. A downward yellow arrow ( ) appearing to the left of the text indicates a pause at the end of the script or function. This allows you to examine variables before returning to the calling function.

Check the values of mu and tot from the Debugger. Highlight the text of each variable and right-click to bring up the context menu and choose Evaluate Selection. Or, alternatively, choose Evaluate Selection from the View menu.

Both the selection and the result are displayed in the Command Window.

K>> mu mu =

3 K>> tot tot =

4

The problem is in the sqsum function.

Changing Workspace Context

Use the Stack pull-down menu in the upper-right corner of the Debugger window to change workspace contexts. To step out from the variance function and see the base workspace contents, select Base Workspace from the menu.

Check the workspace context using whos or the graphical Workspace Browser.

The variables v and myvar1, as well as any other variables you may have created, show up in the listing. To return to the variance workspace context, select Variance from the menu.

Stepping Through Code and Continuing Execution

Clear the breakpoint at line 4 in variance.m by placing the cursor on the line and selecting Clear Breakpoint from the Debug menu. (Or alternatively right-click to bring up the context menu and choose Clear Breakpoint).

Continue executing the M-file by selecting Continue from the Debug menu.

Open the sqsum.m file and set a breakpoint at line 4 to check both the loop indices and the computations that take place inside the loop. Run variance again, still using the vector v as input. Execution pauses at line 4 of sqsum. If

MATLAB Debugger

we look at the variance function in the Editor/Debugger, we see the call to sqsum indicated by an arrow with a vertical line through it.

Evaluate the loop index i. K>> i

i = 1

Then select Single Step from the Debug menu to execute the next line.

Evaluate the variable tot. K>> tot

tot = 4

Select Single Step again. sqsum only goes through the for loop once.

for i = 1:length(mu)

The loop only iterates until the length of mu, a scalar, rather than the length of x, the input vector.

Select Quit Debugging from the Debug menu to end the M-file execution.

To see if changing tot to its expected value produces the correct answer, clear the breakpoint from sqsum and set a breakpoint on line 4 of variance.m. Run variance once again.

variance(v)

Execution pauses after control returns from sqsum, but before variance uses the returned value of tot. From the Command Window, set tot to its correct value of 10.

K>> tot = 10

tot = 10

Select Continue Execution from the Debug menu, and the result is correct.

End the Debug Session

Select the Exit Editor/Debugger from the File menu to end the debugging session.

Debugging from the Command Line

The MATLAB debugging commands are a set of tools that allow you to debug your M-files from the command line. The most general form for each debugging command is shown below.

Description Syntax

Set breakpoint. dbstop at line_num in

file_name

Remove breakpoint. dbclear at line_num in file_name

Stop on warning, error, or NaN/Inf generation.

dstop if warning error naninf infnan

Resume execution. dbcont

MATLAB Debugger

For more information about any of these debugging commands, type help or doc followed by the command name.

Example Command Line Debugging Session

You can perform all debugging tasks from the command line. To follow this example, use the M-files from the beginning of this chapter.

function y = variance(x)function tot = sqsum(x,mu) mu = sum(x)/length(x);tot = 0;

tot= sqsum(x,mu);for i = 1:length(mu)

y = tot/(length(x)–1); tot = tot + ((x(i)–mu).^2);

end Setting Breakpoints

dbstop inserts a breakpoint at a specified line. The M-file halts before the line actually executes. Set breakpoints in variance after the computation of the mean (line 2), and after the computation of the mean-removed squared sum (line 3) using

dbstop variance 3 dbstop variance 4

List function call stack. dbstack

List all breakpoints. dbstatus file_name

Execute one or more lines. dbstep nlines List M-file with line numbers. dbtype file_name Change local workspace context

(down).

dbdown

Change local workspace context (up). dbup

Quit debug mode. dbquit

Description Syntax

Stepping Through Code and Using Keyboard Mode

Take the vector v = [1 2 3 4 5] as example input. The expected values for the mean and the mean-removed squared sum are 3 and10, respectively. See if you get the expected results at the breakpoints. Execute the function from the command line.

variance(v)

MATLAB displays the next line to be executed, and its line number.

3 tot = sqsum(x,mu);

K>>

When execution stops at a breakpoint, you’re automatically in keyboard mode, as indicated by the K>> prompt. At this prompt, you can type standard MATLAB commands. When you’re finished, type dbcont to resume execution.

Note On some platforms, a debugging window may automatically appear when a function stops at a breakpoint.

When execution halts at the first breakpoint, use whos to see what variables are now in the workspace.

whos

To check the value of mu K>> mu

mu = 3

MATLAB Debugger

Use dbstep to step one line in the function. When execution stops again before line 4, check the value of tot to see if the mean-removed squared sum

calculation matches the expected value.

K>> dbstep

4 y = tot/(length(x)–1);

K>> tot tot = 4

It appears the problem may be in the sqsum function.

Changing Workspace Context

Use dbup and dbdown to move between function workspaces and the base workspace. To step up from the variance function and see the base workspace contents, use

dbup whos

The test variable v, as well as any other variables you may have created, shows up in the listing. To step back down to the variance workspace, use

dbdown

Displaying an M-File with Line Numbers

Without leaving keyboard mode, use dbtype to view sqsum. Set breakpoints to check both the loop indices and the computations that take place inside the loop.

K>> dbtype sqsum

1 function tot = sqsum(x,mu) 2 tot = 0;

3 for i = 1:length(mu)

4 tot = tot + ((x(i)–mu).^2);

5 end

K>> dbstop sqsum 4

Viewing the Function Call Stack and Continuing Execution

Return from keyboard mode using dbquit. At the MATLAB prompt, type dbclear variance

to clear the breakpoints from the variance function, while retaining the new sqsum breakpoints.

Run variance again, still using the vector v as input:

variance(v)

4 tot = tot + ((x(i)–mu).^2);

Use dbstack to view the function call stack, verifying that variance did call sqsum.

K>> dbstack

In Pat:Applications:V5:sqsum.m at line 4 In Pat:Applications:V5:variance.m at line 3

Check the value of the loop index i, then the value of tot. After checking tot, dbstep again to check the next value of i.

K>> i i = 1 K>> dbstep 5 end K>> tot tot = 4 K>> dbstep

End of M-file function Pat:Applications:V5:sqsum.m.

The function only goes through the loop once, ending after the first iteration.

From the for statement for i = 1:length(mu)

MATLAB Debugger

you can see that there is a mistake in the line. The loop only iterates until the length of mu, a scalar, rather than the length of x, the input vector.

To see if changing tot to its expected value produces the correct answer, type K>> tot = 10

tot = 10

Use the dbup command to move up one workspace context, into the variance function workspace. It’s clear that the variance function was taking the returned tot value of 4, dividing by length(x)–1, also 4 in this case, and coming up with the incorrect answer of 1. Verify that it comes up with the correct answer now that tot has the correct value, using dbcont to continue execution.

K>> dbup

In workspace belonging to Pat:Applications:V5:variance.m.

K>> dbcont ans = 2.5000

Ending A Debugging Session

Use dbquit to end the debugging session and return to the base workspace.

Edit sqsum.m so that its for statement runs from 1 to length(x) rather than 1 to length(mu).

for i = 1:length(x)

Repeating the original trial run, we now get the expected results:

variance(v) ans = 2.5000 variance(w) ans = 468.3876

Một phần của tài liệu Giáo trình Matlab: using matlab (Trang 85 - 99)

Tải bản đầy đủ (PDF)

(585 trang)