Development Environment |
 |
Debugging M-Files
This section introduces general techniques for finding errors, and then illustrates MATLAB debugger features found in the Editor/Debugger and debugging functions using a simple example. It includes these topics:
Types of Errors
Debugging is the process by which you isolate and fix problems with your code. Debugging helps to correct two kinds of errors:
- Syntax errors - For example, misspelling a function name or omitting a parenthesis. MATLAB detects most syntax errors and displays an error message in the Command Window describing the error and showing its line number in the M-file.
- Run-time errors - These errors are usually algorithmic in nature. For example, you might modify the wrong variable or perform a calculation incorrectly. Run-time errors are apparent when an M-file produces unexpected results.
Finding Errors
Usually, it's easy to find syntax errors based on MATLAB's error messages. Run-time errors are more difficult to track down because the function's local workspace is lost when the error forces a return to the MATLAB base workspace. Use the following techniques to isolate the cause of run-time errors:
- Remove selected semicolons from the statements in your M-file. Semicolons suppress the display of intermediate calculations in the M-file. By removing the semicolons, you instruct MATLAB to display these results on your screen as the M-file executes.
- Add
keyboard
statements to the M-file. Keyboard statements stop M-file execution at the point where they appear and allow you to examine and change the function's local workspace. This mode is indicated by a special prompt, "K>>
." Resume function execution by typing return
and pressing the Return key.
- Comment out the leading function declaration and run the M-file as a script. This makes the intermediate results accessible in the base workspace.
- Use the MATLAB Editor/Debugger or debugging functions. They are useful for correcting run-time errors because you can access function workspaces and examine or change the values they contain. You can set and clear breakpoints, lines in an M-file at which execution halts. You can change workspace contexts, view the function call stack, and execute the lines in an M-file one by one.
The remainder of this section on debugging M-files describes the use of the Editor/Debugger and debugging function using an example.
| Closing M-Files | | Debugging Example - The Collatz Problem |  |