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

조회 수: 58 (최근 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 CenterFile Exchange에서 Debugging and Analysis에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by