MATLAB Programming/Debugging M Files - Wikibooks, open books for an open world (2024)

[MATLAB Programming\|/MATLAB Programming]m]

Chapter 1: MATLAB ._.

 Introductions .
Fundamentals of MATLAB
MATLAB Workspace
MATLAB Variables
*.mat files

Chapter 2: MATLAB Concepts

MATLAB operator
Data File I/O

Chapter 3: Variable Manipulation

Numbers and Booleans
Strings
Portable Functions
Complex Numbers

Chapter 4: Vector and matrices

Vector and Matrices
Special Matrices
Operation on Vectors
Operation on Matrices
Sparse Matrices

Chapter 5: Array

Arrays
Introduction to array operations
Vectors and Basic Vector Operations
Mathematics with Vectors and Matrices
Struct Arrays
Cell Arrays

Chapter 6: Graphical Plotting

Basic Graphics Commands
Plot
Polar Plot
Semilogx or Semilogy
Loglog
Bode Plot
Nichols Plot
Nyquist Plot

Chapter 7: M File Programming

Scripts
Comments
The Input Function
Control Flow
Loops and Branches
Error Messages
Debugging M Files

Chapter 8: Advanced Topics

Numerical Manipulation
Advanced File I/O
Object Oriented Programming
Applications and Examples
Toolboxes and Extensions

Chapter 9: Bonus chapters

MATLAB Benefits and Caveats
Alternatives to MATLAB
[MATLAB_Programming/GNU_Octave|What is Octave= (8) hsrmonic functions]
Octave/MATLAB differences

edit this box

This section explains things you can do if you fix all the syntax errors (the ones that give you actual error messages), the program runs... but it gives you some result you don't want. Maybe it goes into an infinite loop, maybe it goe through the loop one too few or one too many times, maybe one of your "if" statements doesn't work, maybe the program is giving you "infinity" or "NaN" as an answer (which usually isn't very useful!)... there's as many things that can go wrong as there are lines in the code. Thankfully there are techniques for both fixing and improving on working MATLAB code.

Contents

  • 1 Using MATLAB's Debugging tool
  • 2 Using comments to help you debug code
  • 3 How to escape infinite loops
  • 4 Other debugging tips

[edit | edit source]

Using the Debugging Tool will let you stop your program in mid-execution to examine the contents of variables and other things which can help you find mistakes in your program.

M-file programs are stopped at "breakpoints". To create a breakpoint, simply press F12 and a red dot will appear next to the line where your cursor is. You can also click on the dash next to the line number on the left side of the M-file window to achieve the same result.

Then press F5 or Debug->Run from the menu to run the program. It will stop at the breakpoint with a green arrow next to it. You can then examine the contents of variables in the workspace, step, continue or stop your program using the Debug menu. To examine contents of a variable, simply type its name into the workspace, but be warned: you can only look at the values of variables in the file you stop in, so this means that you'll probably need multiple breakpoints to find the source of your problem.

There are several different ways you can move through the program from a breakpoint. One way is to go through the whole program, line by line, entering every function that is called. This is effective if you don't know where the problem is, but since it enters every function (including MATLAB functions like ode45), you may not desire to use it all the time. Thankfully, there's also a way to simply step through the function you're currently stopped in, one line at a time, and instead of going through the child functions line by line MATLAB will simply give you the results of those functions.

Finally, note that you cannot set a breakpoint until you save the M-file. If you change something, you must save before the breakpoint "notices" your changes. This situation is depicted in MATLAB by changing the dots from red to gray. Sometimes, you'll save but the dots will still be gray; this occurs when you have more than one breakpoint in multiple files. To get around this (which is really annoying), you have to keep going to "exit debug mode" until it turns gray. Once you're completely out of debug mode, your file will save and you'll be ready to start another round of debugging.

Using comments to help you debug code

[edit | edit source]

If you want to test the effects of leaving out certain lines of code (to see, for example, if the program still returns Inf if you take them out), you can comment out the code. To do this, highlight it and then go to:

Text -> Comment

Or press CTRL+R. This will simply put a '%' in front of every line; if the line is already commented out it will put another '%' there so when you uncomment them the pattern of comment lines will not change. Commented lines will be ignored by the compiler, so the effect will be that the program is run without them.

To uncomment a line go to

Text -> Uncomment

Or press CTRL+T.

Another use of commenting is to test the difference between two different possible sets of code to do something (for example, you may want to test the effect of using ODE113 as opposed to ODE45 to solve a differential equation, so you'd have one line calling each). You can test the difference by commenting one out and running the program, then uncommenting that one and commenting the other one out, and calling the program again.

How to escape infinite loops

[edit | edit source]

If your program is doing nothing for a long time, it may just be slow (MATLAB creates a lot of overhead and if you don't use arrays wisely it will go very, very slow) but if you are testing a small module, it is more likely that you have an infinite loop. Though MATLAB can't directly tell you you have an infinite loop, it does attempt to give you some hints. The first comes when you terminate the program. Terminate it by pressing CTRL+C and MATLAB will give you a message telling you exactly what line you stopped on. If your program is running a long time, it is likely the line you stopped in is in the middle of an infinite loop (though be warned, if the loop calls a sub-function, it is likely that you will stop in the sub-function and not the parent. Nevertheless, MATLAB also will tell you the lines of the parents too so you can track down the loop easily enough).

However, sometimes MATLAB won't even let you return to the main window to press CTRL-C. In this case you probably have to kill the whole MATLAB process. After this, add a "pause (0.001)" or a similarly small value in the loop you suspect to be the infinite one. Whenever MATLAB passes this instruction you will be able to interact with MATLAB for a (very) short time, e.g. go to the main window and press CTRL-C with MATLAB being able to respond to your command.

Other debugging tips

[edit | edit source]

When inside a function, a loop or just anywhere in the script use a special comment syntax.The%% is the Cell-mode commenting. By adding a%% on the line above the interesting codeand another%% below the code a cell is created. Now this cell may be executed and modified in memory without the requirement to save the code, script or function. By adding some text after the%% a heading for this cell section is created. I.e.%% Start debugging infinite loop

Another method is to enter the breakpoint, selecting the interesting part and copy this to a new file.Now the code may be changed within this new file and tested. When the modified code is working as expected the debug session may be ended. The code from the temporary file may be copied back and replace the debugged code. This method lets the user run this code snippet multiple times include the%% if the code should be run in cell mode.

Instead of using the IDE to run the code, debug the code or selecting breakpoints, command line functions may be used. Just enter db and press the TAB-key to choose the functions. The functions dbstatus and dbstack are two usable functions. Experiment with the functions and use help functon name or select the function name and press the F1-key

The last debugging tips in is to add possible code inside the commentsI.e.% plot(x,y);% This debug plot function plots the value vector y with input xNow select the plot(x,y) with or without the; and press F9 (run the selected code). Use help and preferences to find and modify keyboard shortcuts if needed. CTRL+D on the selected y variable opens it inside the variable editor, not to forget hovering the mouse over any variable will display it contents if possible. Even the plot command itself is a great debugging tool, when it comes to visualize the variables.

The final tips is actually a summary. Experiment with the above methods and even combine them such that the debugged code is both run efficiently, has valuable comments and have means to be debugged if necessary. Make plans for coding mistakes by adding comments and helper functions. Make small functions which does what it is designed to do, then implement this function in the complete program or script.Inside the functions use try, catch me and me.getReport; And if there are recurring mistakes, expect them to happen and program accordingly. Infinite loops are very common mistakes so by adding functionality to discover this mistake is a great time saver. Another tips could be unit testing.

MATLAB Programming/Debugging M Files - Wikibooks, open books for an open world (2024)

FAQs

What is the primary purpose of debugging m files in MATLAB? ›

You can diagnose problems in your MATLAB® code files by debugging your code interactively in the Editor and Live Editor or programmatically by using debugging functions in the Command Window.

What is an option in MATLAB for debugging? ›

Debugging
dbclearRemove breakpoints
dbstepExecute next executable line from current breakpoint
dbstopSet breakpoints for debugging
dbtypeDisplay file with line numbers
dbupShift current workspace to workspace of caller in debug mode
7 more rows

What is the M-file program in MATLAB? ›

An m-file, or script file, is a simple text file where you can place MATLAB commands. When the file is run, MATLAB reads the commands and executes them exactly as it would if you had typed each command sequentially at the MATLAB prompt. All m-file names must end with the extension '. m' (e.g. test.

What is the purpose of M-files? ›

The M-Files system organizes your digital business documents using tags and metadata. This digital indexing, storage, and retrieval system helps anyone in your organization, with proper permissions, to access the latest version of a business document.

How to debug a MATLAB code? ›

Debug Using Keyboard Shortcuts or Functions

Run the current line of code. Run the current line of code, and, if the line contains a call to another function, step into that function. After stepping in, run the rest of the called function, leave the called function, and then pause. End debugging session.

How to use debugging? ›

The five steps of debugging
  1. Step One: Gather information about the error.
  2. Step Two: Isolate the error.
  3. Step Three: Identify the error.
  4. Step Four: Determine how to fix the error.
  5. Step Five: Apply and test.
Jan 25, 2023

How do I stop MATLAB from debugging? ›

MATLAB displays the line where it pauses and enters debug mode. Type dbquit to exit debug mode.

What is the main purpose of debugging? ›

Debugging is the process of finding and fixing errors or bugs in the source code of any software.

What are the benefits of an M file in MATLAB? ›

A MATLAB file of a special format that contains code with optional inputs and outputs is called function M-file. Some advantages: Functions can be called from inside of other script and function M-files. Inputs allow variable values to be modified when calling the function (eg from the Command Window).

What is the purpose of debug mode? ›

Debug is a process used by developers and programmers to identify and remove errors or bugs in software or hardware. It involves going through the code, understanding the flow, and systematically isolating the parts causing the issues. This process helps to ensure the system functions correctly and efficiently.

What is the purpose of the debug menu? ›

Debug menus and rooms are used during software development for ease of testing and are usually made inaccessible or otherwise hidden from the end user.

Top Articles
Latest Posts
Article information

Author: Stevie Stamm

Last Updated:

Views: 5610

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Stevie Stamm

Birthday: 1996-06-22

Address: Apt. 419 4200 Sipes Estate, East Delmerview, WY 05617

Phone: +342332224300

Job: Future Advertising Analyst

Hobby: Leather crafting, Puzzles, Leather crafting, scrapbook, Urban exploration, Cabaret, Skateboarding

Introduction: My name is Stevie Stamm, I am a colorful, sparkling, splendid, vast, open, hilarious, tender person who loves writing and wants to share my knowledge and understanding with you.