user42459
user42459

Reputation: 915

Matlab variable which stores the name of the mfile and line number

For debugging purpose, I want to print out the name of the m-file and the line number so that, when something goes off, it says something like

Error at 197th line of run.m

Given that Matlab displays an error message of this type, there must be a solution.

How can I do this?

===========Follow-up question==============

Thank you! But I got a follow-up question.

I have main.m which is the main m-file and main.m calls lower.m

I wrote

info = dbstack()

and

try 
    error('Toto')
catch ME
    ME.stack
end

to the main.m. Then Matlab displays

info = 

    file: 'main.m'
    name: 'main'
    line: 15

ans = 

    file: 'C:\Users\account1\Google Drive\1AAA-RA\11HHJK(O…'
    name: 'main'
    line: 18

However, when I write dbstack and try-catch thing to lower.m, then Matlab does not display any exact information.

I ran the main.m and main.m called the lower level m-file but it doesn't display any information.

info = 

2x1 struct array with fields:

    file
    name
    line

ans = 

2x1 struct array with fields:

    file
    name
    line

What should I do to make it display every file, name, line information?

Ideally, Matlab will display the information of both main.m and lower.m like the following:

    file1: 'main.m'
    name1: 'main'
    line1: 15
    file2: 'lower.m'
    name2: 'lower'
    line2: 6

Is this possible?

Upvotes: 0

Views: 116

Answers (3)

Toothpick Anemone
Toothpick Anemone

Reputation: 4644

info = dbstack();

% info is now a struct that has 3 fields

% info.file
% is a string containing the file name in which the function appears.

% info.name 
% is a string containing the name of the function within the file.

% info.line
% is the line number on which dbstack was called

Upvotes: 1

Toothpick Anemone
Toothpick Anemone

Reputation: 4644

MATLAB's error function will automatically display the filename and line number.

function [ ] = wsgefiow9ey(  )
n = 7;
if n > 1
    msg = 'Error: n is too big.';
    error(msg)
end % if
end % function definition

click here to see console output resulting from call to MATLAB error function

Upvotes: -1

Thierry Dalon
Thierry Dalon

Reputation: 926

You can use the Matlab Exception object. The line information is contained in the 'stack' property.

Example create a 'test.m' script:

try
    error('Toto')
catch ME
    ME.stack
end

Output of command window is:

>> test

ans = 

    file: 'D:\MATLAB\Sandboxes\AVLab\test.m'
    name: 'test'
    line: 2

Or without a try/catch you can use MException.last.

See documentation link http://www.mathworks.com/help/matlab/matlab_prog/capture-information-about-errors.html

Upvotes: 1

Related Questions