Matlab Training Session 15: Debugging Strategies - PowerPoint PPT Presentation

1 / 50
About This Presentation
Title:

Matlab Training Session 15: Debugging Strategies

Description:

Matlab Training Session 15: Debugging Strategies Course Website: http://www.queensu.ca/neurosci/Matlab Training Sessions.htm ... – PowerPoint PPT presentation

Number of Views:346
Avg rating:3.0/5.0
Slides: 51
Provided by: Rob154
Category:

less

Transcript and Presenter's Notes

Title: Matlab Training Session 15: Debugging Strategies


1
Matlab Training Session 15Debugging Strategies
Course Website http//www.queensu.ca/neurosci/Mat
lab Training Sessions.htm
2
  • Course Outline
  • Term 1
  • Introduction to Matlab and its Interface
  • Fundamentals (Operators)
  • Fundamentals (Flow)
  • Importing Data
  • Functions and M-Files
  • Plotting (2D and 3D)
  • Term 2
  • Term 1 review
  • Plotting (2D and 3D)
  • Statistical Tools in Matlab
  • Nonlinear Curve Fitting
  • Statistical Tools in Matlab II
  • GUIs
  • Improving Code Efficiency
  • Debugging Strategies

3
  • Week 14 Lecture Outline
  • Debugging Strategies
  • General Concepts
  • B. Basic Bug Types
  • M-Editor Built in Debugger (M-Lint)
  • Debug Mode/Debugging Command
  • Common Coding Errors and Error Messages

4
Part A General Concepts
  • A bug is a program flaw. Originated when a
    moth got stuck in an early computer at Harvard
    University.
  • Debugging code is both an art and a science
    and can employ many different strategies.
  • Requires practice and patience!

5
Part A General Concepts
  • The most important and simplest technique in
    debugging is variable inspection
  • Because most software bugs arise from the
    incorrect use of variables, inspection of
    variables during program operation is the most
    common debugging technique.

6
Part A General Concepts
  • There are many ways to inspect variables
  • - Omit semicolon at end of line to output
    results
  • - Use disp() function
  • - For larger arrays, vectors or matrices plot
    results
  • Usually errors occur because a variable(s)
    contains something other than what was intended.
  • Inspection of any variable within the workspace
    can be accomplished at any time during execution
    by setting breakpoints within an m-file
  • It can be helpful to run functions as a
    script to make all variables easily available to
    the workspace for variable inspection

7
Part A General Concepts
  • Error vs Warning Messages
  • Matlab indicates coding issues via messages
    printed to the command line before, during or
    after program execution.
  • Warning messages are colored black and indicate
    potential problems/issues and do not interfere
    with code execution
  • Since warnings do not effect code execution,
    they do not have to be fixed if they are deemed
    unimportant
  • Errors messages are colored red and are
    generated when problems are sever enough to cause
    program execution to abort
  • Errors must be fixed in order for code to
    execute

8
Part A General Concepts
  • Error vs Warning Messages
  • Unimportant warning messages can be disabled
  • To Disable all warning messages
  • Warning off
  • To Enable all warning messages
  • Warning on
  • To disable individual warning messages
  • gtgt 6/0
  • Warning Divide by zero.
  • ans
  • Inf
  • gtgt warning('off','MATLABdivideByZero')

9
Part A General Concepts
  • The Stack
  • Functions can call other functions, which in
    turn call other functions.
  • When an error occurs, MATLAB provides an error
    message that displays the "stack (i.e. a list
    of the function where the error occurred, as well
    as all other parent function(s) that called that
    function).
  • These error messages can be confusing as
    beginners may find it difficult to determine
    where the problem actually occurred.

10
Part BBasic Bug Types
There are Three Main Types of Bugs 1.
Typographic errors 2. Syntax errors 3.
Algorithmic errors
11
Part BBasic Bug Types
Typographic errors
  • A typo, or typographic error, is a simple
    typing error.
  • Function name typos are usually easy to find
  • Variable name typos, can be hard to find and
    can lead to unexpected errors much later in your
    code
  • Example 1
  • cod(pi)
  • when you meant to type
  • cos(pi)
  • ??? Undefined function or variable 'cod'.

12
Part BBasic Bug Types
Typographic errors
  • A typo, or typographic error, is a simple
    typing error.
  • Function name typos are usually easy to find
  • Variable name typos, can be hard to find and
    can lead to unexpected errors much later in your
    code
  • Example 2
  • xcos(y)
  • when you meant to type
  • xcos(t)
  • If t is a different size than y, you will get
    an error message about the size of the x when
    you call it later in your code

13
Part BBasic Bug Types
Typographic errors
  • Furthermore, if you utilize a function or
    variable name that is identical to a built in
    function or variable in matlab (or any installed
    toolbox), this can lead to errors unrelated to
    your code.
  • Avoid these mistakes by
  • Add code and data paths to top and not bottom
    of the matlab search path to ensure built in
    function names will not be executed first
  • Use the which function to confirm that the
    intended function will be executed

14
Part BBasic Bug Types
Syntax errors
  • A syntax error results when the order,
    structure, or form of a function call is
    incorrect
  • Can occur when a function is called with inputs
    that are the wrong shape, size, and/or type or
    are otherwise not valid
  • Example
  • gtgt cos('ten')
  • ??? Undefined function or method 'cos' for input
    arguments of type 'char'.
  • Deciphering syntax related error messages can
    sometimes be difficult, and tracking down where
    the problem originated can be even harder.

15
Part BBasic Bug Types
Algorithmic errors
  • An algorithmic error occurs when a program
    completes its execution, but the results are
    unintended or unexpected.
  • For example you wrote a program to add two
    numbers, passed it 2, 3 and received 6 as a
    result with no error or warning messages.

16
Part BBasic Bug Types
Algorithmic errors
  • There are 2 Standard techniques for debugging
    algorithmic errors
  • Compute the answer you expect to the problem by
    some means other than MATLAB or by using an
    existing working example to ensure the
    algorithmic principle is correct
  • Step through the code to verify that the
    algorithm computes the correct result at each
    stage
  • This requires a step-by-step inspection of
    variables at each stage of the incorrectly
    executing m-file.

17
Part CM-Editor Built in Debugger (M-Lint)
  • What Is the M-Lint code Analyzer?
  • The M-Lint code analyzer is available in Matlab
    Version 7 and higher.
  • M-Lint checks your code for problems and
    recommends modifications to maximize performance
    and maintainability.
  • Interface is similar to the Microsoft Word
    automatic spelling and grammar checker, but with
    more features and power

18
Part CM-Editor Built in Debugger (M-Lint)
M-Lint can be used to report problems and
recommendations in 2 ways 1. Continuously check
code in the editor while you work. 2. Create a
report for an existing M-file or group of
M-files.
19
Part CM-Editor Built in Debugger (M-Lint)
  • 1. Continuously check code in the editor while
    you work.
  • M-Lint highlights or underlines errors,
    warnings, and suggestions in the body of the code
    and provides an overview in the right hand column
  • The code analyzer updates automatically and
    continuously so you can see if your changes
    addressed the indicated issues.
  • For some issues/problems, M-Lint offers
    automatic code correction.

20
Part CM-Editor Built in Debugger (M-Lint)
  • Create a report for an existing M-file or group
    of M-files.
  • To do so, from an M-file in the Editor, select
    Tools gt M-Lint gt Show M-Lint Report.
  • After making changes, you must save the file
    and rerun the report to see if your changes
    addressed the issues noted in M-Lint messages.

21
Setting Preferences
22
Part CM-Editor Built in Debugger (M-Lint)
  • M-Lint Message Indicators
  • The M-Lint message indicator at the top right
    edge of the window conveys the M-Lint messages
    reported for the file
  • Red means syntax errors were detected.
  • Orange means warnings or opportunities for
    improvement were detected, but no errors were
    detected.
  • Green means no errors, warnings, or
    opportunities for improvement were detected.
  • For example, when the indicator is red there is
    at least one error in the file.

23
Part CM-Editor Built in Debugger (M-Lint)
  • Using the M-Lint Interface
  • Double click on orange or red lines in right
    column to find error location
  • Right click over highlighted or underlined code
    for automatic correction or ignore problem
    options
  • Once changes are made M-Lint updates
    automatically, even if you do not save the file.
  • Some errors and warnings are highlighted,
    indicating M-Lint can automatically fix the code.

24
Part D Debug Mode
  • What is debug mode?
  • Sometimes program bugs are not located at the
    line where error/warning message was generated
    but was propagated from earlier code.
  • In other cases algorithmic errors may have
    occurred without any outward error/warning
    messages ever being produced.
  • In order to debug such situations the user must
    search step-by-step for the problematic code
    using variable inspection

25
Part D Debug Mode
  • Debug mode provides tools for pinpointing the
    location of erroneous code by
  • Allowing the user to halt execution of code at
    any point and examine the state of all variables
  • Allowing line by line step-by-step execution of
    code
  • Enabling the examination of different workspaces
    in the stack from nested functions
  • MATLAB Debug mode can be used from both the
    m-editor and the command line

26
Part D Debug Mode
Debugging from the editor Setting Breakpoints
The insertion of breakpoints causes MATLAB to
enter debug mode (indicated by the Kgtgt prompt in
the command line). When a breakpoint is
encountered in the code, matlab halts execution
at the previous line and allows all variables
currently in the workspace to be examined.
27
Part D Debug Mode
Debugging from the editor Setting
Breakpoints You can set breakpoints in the
editor in five different ways 1. Clicking on
the horizontal line next to the line number 2.
Click on the set breakpoint button to set a
breakpoint at the cursor location 3. Selecting
Set/Clear Breakpoints from the Breakpoints
pull down menu 4. Right click on any line of
code 5. Press the F12 button
28
Part D Debug Mode
Once in debug mode there are several options
29
Part D Debug Mode
  • Step
  • Step through your code one line at a time. F10
    (Windows) or F6 (UNIX)

30
Part D Debug Mode
  • Step In
  • Open the first function called on the current
    line and step through that function. F11
    (Windows) or F7 (UNIX/Linux)
  • Compiled functions will be ignored

31
Part D Debug Mode
  • Step Out
  • Return from a stepped into function without
    executing each of the remaining lines in the
    function individually. Shift-F11 (Windows) or
    Shift-F7 (UNIX/Linux)
  • When you step out of a function, you will
    still be in debug mode within the parent function

32
Part D Debug Mode
  • Continue
  • Once in debug mode, the Run button will
    continue execution until the next breakpoint,
    error, or until the code is finished.
  • Alternatively you can execute a section of code
    from the current point to some other point
    (without setting a breakpoint)
  • This can be done by positioning the cursor at
    the point where you want execution to end and
    select Go until cursor from the Debug menu.

33
Part D Debug Mode
  • Exit Debug Mode
  • Once your error has been located and corrected
    this will halt program execution and exit debug
    mode.

34
Part D Debug Mode
Debugging from the Command Line Some useful
debugging commands dbstop - Set breakpoint
dbclear - Remove breakpoint dbcont - Resume
execution dbstack - List who called whom
dbstatus - List all breakpoints dbstep -
Execute one or more lines dbquit - Quit debug
mode These debugging commands work on
functions, not scripts. For a complete list of
debugging commands type help debug
35
Part D Debug Mode
  • dbstop in m-file
  • Set a breakpoint on the first executable line
    of the m-file.
  • Example dbstop in test sets a breakpoint on the
    first executable line of test.m
  • dbstop in m-file at line number
  • Set a breakpoint in the m-file on line number
    line number.
  • Example dbstop in test at 10

36
Part D Debug Mode
  • dbstop if error
  • Set prior to running m-file.
  • If an error is encountered, enter debug mode
    and open the m-file in the editor at the line
    where the error occurred.
  • dbstop if warning
  • Set prior to running m-file.
  • If a warning is encountered, enter debug mode
    and open the m-file in the editor at the line
    where the warning occurred.

37
Part D Debug Mode
  • dbclear all in m-file
  • Clear all breakpoints and stop conditions in
    the specified m-file.
  • dbclear all
  • Cear all breakpoints and stop conditions in all
    active m-files.

38
Part D Debug Mode
  • dbstep
  • Execute one line of code and remain in debug
    mode.
  • dbstep N
  • Execute the next N lines of code (N must be a
    positive integer).

39
Part D Debug Mode
  • dbstep in
  • If the next line to be executed is a call to
    another function, open that function in the
    editor and stop at the first line.
  • dbstep out
  • Execute the rest of the lines in the current
    function, then return to the calling function and
    stop on the line immediately after the function
    call.

40
Part E Common Errors and Error Messages
  • Run time errors occur when MATLAB is forced to
    halt execution due to some kind of typographic,
    syntax, or algorithmic error.
  • When this occurs a red error message is printed
    to the command line indicating the file and line
    number where the error occurred. Eg
  • ??? Error using gt ones
  • Too many input arguments.
  • Error in gt /work/test.m
  • On line 10 gt A ones(n,n,n)
  • The first part explains the error, the next
    gives the location of the error. Errors will be
    listed in the order of the stack from the parent
    function to the child function.
  • If you are not executing a saved m-file then
    the error message will not give you any file
    location information.

41
Part E Common Errors and Error Messages
  • Variable size or type mismatch
  • Refers to errors in which a variable is
    assigned the value of a matrix that is the wrong
    size (i.e. in number of rows and columns) or of
    the wrong type (i.e. string versus number.)
  • These are perhaps the most common of all,
    beyond simple errors of command syntax.

42
Part E Common Errors and Error Messages
Variable size or type mismatch
  • Often occurs during the passing of variables
    to/from functions that assume an argument will
    have a particular size and shape.
  • If that variable that is used does not have
    exactly the right dimensions, an error occurs.
  • Eg. If a vector of the correct length is being
    assigned, it may make a difference whether the
    vector is passed as a row vector versus as a
    column. This error can be solved by transposing
    the variable ( operator).

43
Part E Common Errors and Error Messages
Variable size or type mismatch
Example
gtgt a zeros(5,2)gtgt a(3,) 1 2 3??? In an
assignment A(matrix,) B, the number of columns
in A and Bmust be the same. gtgt a
zeros(5,2)gtgt a(,1) 1 2 3 4 5??? In an
assignment A(,matrix) B, the number of
elements in the subscript of A and the number of
columns in B must be the same.
44
Part E Common Errors and Error Messages
Variable size or type mismatch
Example
gtgt a zeros(5,2)gtgt a(3,) 1 2 3??? In an
assignment A(matrix,) B, the number of columns
in A and Bmust be the same. gtgt a
zeros(5,2)gtgt a(,1) 1 2 3 4 5??? In an
assignment A(,matrix) B, the number of
elements in the subscript of A and the number of
columns in B must be the same.
  • Use the debugger or MATLAB's size command to
    check variables dimensions
  • To check the size of an variable returned by a
    function that is not assigned, assign it to a
    temporary variable

45
Part E Common Errors and Error Messages
Argument size, number, or type mismatch
  • Passing or receiving the incorrect number of
    arguments to a function is another common error

46
Part E Common Errors and Error Messages
Argument size, number, or type mismatch
Example 1
gtgt value, index, extra max(randn(20,10))???
Error using gt maxToo many output arguments.
The max function returns at most two
arguments
47
Part E Common Errors and Error Messages
Argument size, number, or type mismatch
Example 2
gtgt x randn(1,5)gtgt y 2xgtgt p,s
polyfit(x,y) ??? Input argument 'n' is
undefined. Error in gt /usr/local/matlab/toolbox/
matlab/polyfun/polyfit.mOn line 57 gt V(,n1)
ones(length(x),1)
The polyfit function fits a polynomial to
(x,y) data. It requires three arguments for x, y,
and order of the polynomial
DO NOT misinterpret this message to mean that
MATLAB's polyfit function has a software bug in
it!!
48
Part E Common Errors and Error Messages
Count-off-by-one and indexing errors
  • A common error when using loops is to be "off
    by one", i.e. for the loop counter to be in error
    by one when starting or stopping the loop, or
    when using the loop counter to index data.
  • This can result in executing a loop either one
    more or one less time than intended.
  • These can lead to indexing errors within loops.
  • For example in C, the first element has an
    index of '0 in MATLAB the first element has
    index 1.

49
Part E Common Errors and Error Messages
Count-off-by-one and indexing errors
Example 1
gtgt for c 05result(c) 2pic.2end???
Index into matrix is negative or zero.
  • Here the programmer is interested in varying a
    variable from 0 through 5, and makes the mistake
    of using this variable as a vector index as well

50
Part E Common Errors and Error Messages
Count-off-by-one and indexing errors
Example 2
  • gtgt for c 10.55result(c) 2pic.2end
  • Warning Subscript indices must be integer
    values.
  • A non-integer parameter as a vector index will
    produce a warning only.
  • Execution will proceed, but without correct
    matrix indexing. In this example, results are
    only put into the result matrix every other
    iteration when the loop counter c is equal to an
    integer.
  • Part E examples adapted from
  • http//www.ieee-uffc.org/ultrasonics/software/Matl
    ab/Lecture8/Lecture8.htm
Write a Comment
User Comments (0)
About PowerShow.com