I have this question which has been bugging me for some time and I could not find an answer to it.
I'm currently working with a colleague on a Matlab code which is quite long. We each work on different parts of the code without interfering with one another. In order to better orient myself in the code and follow the flow of the program, I put a few disp() so that I know when the code reaches some line.
Eg:
% code
disp('You have reached line 1000')
% code...
However it can be bothersome when I or my colleague add/remove/modify lines of code above the disp() command, so that the line I manually entered in the disp() is no longer accurate.
My question: Is there a way to print the actual line number in the code that the program has reached? It might be a very naive question but I'd like to know if it is at all possible.
There is no goto function in MATLAB. For this application rather than having your function call itself recursively just use a while loop.
To display text in the Command Window, use disp or fprintf.
The command-line interface provides an interactive environment that you can extend. The MATLAB command-line interface includes: Environment — Configure target computers and change the environment properties without using a graphical interface.
You can check dbstack. Here is the doc with examples, depending on what you want to print: http://www.mathworks.co.uk/help/matlab/ref/dbstack.html
Quick example, that you can put in a file debug_point.m
:
%// Tested on Octave only, Matlab might be slightly different
function debug_point()
d = dbstack(1);
d = d(1);
fprintf('Reached file %s, function="%s", line %i\n', d.file, d.name, d.line)
end
Then you can call this function. You can easilly turn off all the prints by changing this function only.
I think there is no simple way to get the line number and present it.
That being said, I usually deal with the situation like this:
Rather than displaying (or writing to a log) on which line the code currently is, I display what the code is currently doing. Something like this:
% code
disp('Accepting answer on Stack Overflow')
% code...
Of course you would still need to worry if your codes functionality suddenly changes, but that requires carefull handling anyway.
If you really really want to show the line number, this is the easiest I could come up with:
%LineNumberForDisplay<123>
This 'update' would then need to take place before each run or after each alteration, which makes it a bit unpractical.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With