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

40 ビュー (過去 30 日間)
Tolulope
Tolulope 2013 年 1 月 15 日
回答済み: Geoffrey May 2022 年 9 月 27 日
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.

回答 (4 件)

Wayne King
Wayne King 2013 年 1 月 15 日
Look at the help for dbstop
For example:
dbstop in FILESPEC at SUBFUN

Image Analyst
Image Analyst 2013 年 1 月 15 日
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 件のコメント
Haim
Haim 2022 年 5 月 17 日
  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 2022 年 5 月 17 日
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?

サインインしてコメントする。


Pruthvi G
Pruthvi G 2019 年 3 月 20 日

Geoffrey May
Geoffrey May 2022 年 9 月 27 日
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().

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by