How does one identify the current line being evaluated during execution?

40 views (last 30 days)
I would like to know if there is a command in MatLab that returns the value of the line number on which it has been executed.
For example:
1
2 for i = 1:10
3 % some line of code
4 currentLine = ?;
5 end
6
7
8
9
Where "?" is some MatLab command or function (if it exists) that identifies the line on which "?" is called, in this case line number 4.

Answers (4)

Wayne King
Wayne King on 15 Jan 2013
Look at the help for dbstop
For example:
dbstop in FILESPEC at SUBFUN

Image Analyst
Image Analyst on 15 Jan 2013
I don't know why you need the number. You can issue the "echo on" command and it will spit out the current line being executed to the command window, without a line number though. When you have functions and other m-files, the concept of line number becomes not so clear.
  2 Comments
Haim
Haim on 17 May 2022
  1. You need the line number for debugging a very heavy undocumented matlab simulation code, since puting comments moves the old lines to unknown new place.
  2. you can simply add the following
lstr = struct(dbstack).line ; % get line number for debugging
str= ['(' num2str(lstr) ') function xxx, <any description string>']; % identify function with the code line number
disp(str);
Image Analyst
Image Analyst on 17 May 2022
Where would you put that. He says he wants "the line number on which it has been executed." which, to me, means he has an existing script that he want to run and somewhere (command window perhaps) he wants to run the file and then have every line printed somewhere with it's line number as it's being executed. Of course only some of the lines in the program get executed, and some (like in a loop) might get executed very many times. I don't see how your code will do that. Let's say my script is
a=10
b=5
if b > 10
fprintf('big b\n')
else
fprintf('small b\n');
end
for k = 1 : 3
a = a+1
end
Some of those lines get executed one or more times and some don't get executed at all. How would you, without altering the original program of course, get only the line of code that actually got executed to appear somewhere with their line number prefixed?

Sign in to comment.


Pruthvi G
Pruthvi G on 20 Mar 2019

Geoffrey May
Geoffrey May on 27 Sep 2022
In case you are like me and trying to programmatically do a dbstop that will adjust as you add lines above it:
stack = dbstack();
stopText = strsplit(sprintf('in %s at %d', stack.name, stack.line + 3));
dbstop(stopText{:});
stopHere = 1;
This will add a breakpoint at the last line of the block, provided that it stays 3 lines below the call to dbstack().

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!