Bill Cheatham
Bill Cheatham

Reputation: 11917

Make MATLAB show location of error when running in cell mode

I usually run my code, at the top level, from scripts. Say I have a script my_error_script.m like so:

my_mat = (1:100) / 2;
idx = my_mat(21);
my_mat(idx) = 4;

When I run this from the matlab prompt, I get the following output:

Attempted to access my_mat(10.5); index must be a positive integer or logical.

Error in my_error_script (line 3)
my_mat(idx) = 4;

An error has occured, and it is clear where this occurred (i.e. line 3). When running scripts that are quite large, this is useful information.

Often I run just a section of a script in cell mode (now called code sections, I think):

% < blah >

%% Run just this cell
my_mat = (1:100) / 2;
idx = my_mat(21);
my_mat(idx) = 4;

%% 

% < blah >

In this case, I am not shown the location of the error:

Attempted to access my_mat(10.5); index must be a positive integer or logical.

This can make it very frustrating to track down errors in longer scripts, even if they are only 10-20 lines long.

Apart from putting the script into a function (which is not always ideal) or adding in disp statements at various points in the loop, what can be done to show the line number or location of the error?

Turning on dbstop if error doesn't even pause the script at the correct location.

Upvotes: 1

Views: 372

Answers (1)

Dan
Dan

Reputation: 1175

I believe the short answer to your question is, currently, "nothing."

This is a known limitation of Matlab acknowledged by the MathWorks. Enabling line numbers with error messages in cell mode (now renamed Code Sections) is apparently on the list for future release. However, it has been on the list since at least 2008 and an implementation timeline seems unclear.

Basically, your only option is to use something other than Code Sections if you want line numbers with your errors. Suggested workarounds include:

  • Highlight small chunks of code and pressing F9 to evaluate the selection (you still won't get line numbers but it will be restricted to a smaller chunk of code)
  • Create more, smaller cells and run them sequentially (same as above)
  • Run the code from the top (you will get line numbers but will lose Code Sections functionality)
  • Restructure your code so you don't use code sections

As you have found, normal debugging tools don't work with Code Sections, either.

Upvotes: 2

Related Questions