Get the actual string executed in Matlab code

I have this question that has been listening to me for some time, and I could not find an answer to it.

I am currently working with a colleague on Matlab code, which is quite long. We work in different parts of the code without interfering with each other. To better navigate the code and keep track of the program flow, I put a few disp () so that I know when the code reaches a certain line.

For instance:

% code disp('You have reached line 1000') % code... 

However, it can be annoying when my colleague or I add / remove / modify lines of code above the disp () command, so the line entered manually in disp () is no longer accurate.

My question is : Is there a way to print the actual line number in the code that the program has reached? This may be a very naive question, but I would like to know if this is possible.

+6
source share
2 answers

You can check dbstack. Here is a document with examples, depending on what you want to print: http://www.mathworks.co.uk/help/matlab/ref/dbstack.html

A quick example that you can put in the debug_point.m file:

 %// 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 easily turn off all prints just by changing this feature.

+7
source

I think there is no easy way to get the line number and present it.

However, I usually deal with a situation like this:

Instead of displaying (or writing to the log) what line the current code is on, I show what this code does. Something like that:

 % code disp('Accepting answer on Stack Overflow') % code... 

Of course, you still need to worry about the functionality of your codes suddenly changing, but this requires careful processing.


If you really want to show the line number, this is the easiest way:

  • Add something with a recognizable pattern, for example: %LineNumberForDisplay<123>
  • Run a script that goes through the file, finds these patterns and replaces the number with the correct one

This update will need to be done before each run or after each change, which makes it a little impractical.

+3
source

Source: https://habr.com/ru/post/974165/


All Articles