Seeing which part of code MatLab is currently running [duplicate] - matlab

Is there any way to stop the execution of a matlab program from the debugger like ctrl+c does, but then being able to continue execution (like you can in say c#)?
If not, is there any better way to workaround this other than trying to pre-emptively set break points or dbstop statements in your matlab code?
I would like to be able to interrupt a long running simulation to look at the current state and then continue the simulation.
The two options I'm currently using/considering are
dbstop commands (or (conditional) breakpoints) in the code.
Drawback is that sometimes I don't want to stop the simulation for a few hours, sometimes want to stop after only a few seconds (and I don't necessarily know that in advance) and this doesn't work well with this approach: If I set the break condition to break every 5 minutes, I can't leave matlab running for hours without interaction. If I set the condition to higher, I have to wait too long for the condition to hit.
include code to save the workspace every few seconds/minutes and import the workspace into a second matlab instance. Drawback is that this is a huge hassle and also doesn't necessarily allows me to resume the simulation with the state of the saved workspace then step through the code for a few iterations.
I'm hoping there is a better solution than either of the 2. Thanks for any advice!
Edit: I think what I'm going to do is write simple matlab function that checks an environment variable or a file on disk every iteration and calls dbstop if I set a flag in this file or env. This way I can control when (and if needed which of several) the breakpoint hits from outside matlab by editing the file. Messy, but should work.

This is not necessarily the best way, but you could simulate a file-based signal/interrupt framework. It could be done by checking every once in a while inside the long simulation loop for the existence of a specific file. If it does, you enter interactive mode using the keyboard command.
Something along the lines:
CHECK_EVERY = 10; %# like a polling rate
tic
i = 1; %# loop counter
while true %# long running loop
if rem(i,CHECK_EVERY) == 0 && exist('debug.txt','file')
fprintf('%f seconds since last time.\n', toc)
keyboard
tic
end
%# ... long calculations ...
i = i + 1;
end
You would run your simulation as usual. When you would like to step in the code, simply create a file debug.txt (manually that is), and the execution will halt and you get the prompt:
2.803095 seconds since last time.
K>>
You could then inspect your variables as usual... To continue, simply run return (dont forget to temporarily rename or remove the file). In order to exit, use dbquit
EDIT: Just occurred to me, instead of checking for files, an easier solution would be to use a dummy figure as the flag (as long as the figure is open, keep running).
hFig = figure; drawnow
while true
if ~ishandle(hFig)
keyboard
hFig = figure; drawnow
end
%# ...
pause(0.5)
end

With the release of R2016a, you can just hit the Pause button in the code editor and it will halt right away. The keyboard shortcut is Ctrl+F5.
To pause the execution of a program while it is running, in the Editor tab, click the Pause button. MATLAB pauses execution at the next executable line*.
When your code is running, the Start button will turn into a pause:
Another change with this release is the ability to add/remove breakpoints while running. Previously you couldn't do this, apparently.

You can set a conditional breakpoint in the MATLAB Editor. You can also use DBSTOP to do this. For example, this will set a conditional breakpoint in the file myFcn at line 20 which will stop execution when a loop variable i is a multiple of 500:
dbstop in myFcn.m at 20 if rem(i,500) == 0
Then you can continue execution after you inspect some of your variables.

If saving the workspace to a file is a good proxy for what you want, how about making a simple GUI with a toggle button. In your code, check the state of the button. If the button is depressed, save the state, update a static text to reflect time stamp of last save, unpress the button. Optionally, have a conditional breakpoint based on the state of that toggle button.

Here is an alternate solution using the waitinput File Exchange submission.
The advantage is that you can use it from whithin the current session or in cases where it is troublesome to set up a file. Also it won't leave a file behind on the computer.
The downside is there as well unfortunately, you need to wait for the checking moment before you can terminate and it costs a little bit of time.
for t = 1:10
pause(3) %Doing some calculations
str = waitinput('Enter 1 if you want to stop ',5);
if ~isnan(str)
keyboard; % Enter dbcont if you want to continue from here
end
['moving on, it is now: ' datestr(now)]
pause(3) %Doing some more calculations
end
If you want, you can prevent lines being printed to the screen. In this case you need to enter the input at the time the figure window is open (Look in your start bar on windows).
To summarize, the short code that you can put somewhere like a conditional breakpoint would be:
if ~isnan(waitinput('',5))
keyboard;
end

After certain version (I don't know which one exactly):
Windows: Ctrl + F5
Mac: Command + F5 (I guess)
Unix: I am looking for answer too
After 2016a, there is a button for that on the interface too.

Related

How to use pause with openvar in a for loop

Using the following code:
tmpTable = table([1;2;3]);
for i = 1:5
openvar tmpTable
pause
end
When I run the for loop, all I get is a blank screen in the Variable Editor, except the dimensions of the table are displayed correctly. If I break from the for loop the table displays correctly.
My question is, how do I make this table display programmatically in the for loop, with a pause like command that allows me to inspect the table before moving onto the next one?
What's happening is that pause is pausing the main MATLAB thread which is why you aren't seeing anything in the Variable Editor. You have to make MATLAB enter debug mode if you want the main MATLAB thread to be free.... or of course break the loop as you have discovered.
A "hackish" way to get things going is to insert a keyboard statement instead of pause to force MATLAB to go into debug mode. Once you're there, you'd have to use dbcont to continue onto the next iteration of the loop. This will make MATLAB enter debug mode again as the keyboard statement will be encountered again thus freeing the main thread. This repeats until the last iteration.
Therefore:
tmpTable = table([1;2;3]);
for i = 1:5
openvar tmpTable
keyboard; %// Change
end
You will then see K>> once you execute the first iteration of the loop when you look at the Command Prompt. This signifies that you are in debug mode. To proceed to the next iteration, type in dbcont in the Command Prompt and push ENTER. You can reuse the last command by pushing the Up arrow on your keyboard then push ENTER again and keep doing this until the last iteration of your loop. You will unfortunately have to click back in the Command Prompt as the focus will be placed on the Variable Editor before you enter in the command again. If at any time you want to quit debug mode, use dbquit. This will terminate any code execution and bring you back to the Command Prompt.
This is the only way really to free up the main MATLAB thread at each iteration that I know of.

Pause Matlab without breakpoint

I have a script that is running a lot more time than I expected, it has been running for the last 3 days and only achieved 55% progress.
I would be perfectly happy to stop it at about 67% (I can live without the remaining 33%) But If I stop it now (ctrl+c or ctlr+break), I will lose all the data.
So is there a way to pause Matlab, perhaps into debug mode so I can check the variables without losing data?
The command (needs to be input manually before you start your function!)
dbstop if error
should catch a ctrl-c and leave you in debug mode.
I assume that you are doing something iteratively here and not relying on a built-in matlab function.
The way I usually solve the issue you have is to have an iteration counter and an if statement on that counter - when the condition is met, the statement has a breakpoint.
Something like this:
itCounter = 0;
itHalt = 100;
while (someCondition)
if (itCounter == itHalt)
itCounter = 0; %<= Put a breakpoint here
else
itCounter = itCounter+1;
end
% Here you calculate away whatever you need to calculate
end
This way, in every itHalt iterations you get a breakpoint. Also, since we're dealing with matlab, you can change the value of itHalt as you see fit as soon as the breakpoint is hit.
I'm thinking to an alternative solution:
Let's have a script which basically consists of a main loop.
The script periodically writes information about the execution status (e. g. the number of iteration done) into a log file.
Also, the script periodically reads a number from the input file
1 meaning "continue"
0 meaning "stop the script execution"
At the beginning of the simulation, 1 is written in the file.
The user can read the log and can decide, at a certain point, to stop the script.
To do it, he has just to change 1 to 0 in the file as save it.
An if section exemines the value read on it.
If 1, nothing appens and the script continues running.
If 0, a break statement terminates the main loop and the script stops.
Just before the break statement, in the if section, the script saves the whole workspace into a .mat file.
The user has now access to MatLab (he can evan close MatLab) and can look, for example, at the output files generated up to that moment by the script, process them, make somo plot and so on.
Then he might decide to continue the execution of the script from the point in which it has been stopped.
At the begining of the script, a variable controls the way the script has to be executed:
Mode 0: start from the beginning
Mode 1: resume the script
An if - else section maneges the user selection.
In particular, if Mode 1 is selected, the script loads the previously saved workspace (stored in a .mat file), then the value of some variables of the script are set to the old values.
As an example: the script was stopped when the index of the for loop was, say, 100.
if the for loop is defined as
for i=start_loop_1:100000
in the Mode 1 of the if, start_loop_1 is set to i+1 (the value of i was saved in the .mat file).
This allows the loop "continuing" the execution from the point in which it was stopped.
In order to effectively "resume" the running of the script, some other variables used in the script might require to be managed in the same way in the Mode 1 section.
In tha case of a "big", "complicated" script this might be difficult, but ... not impossible
This solution has been implemented in the following script.
I can see a potential criticality consisting in the unlucky case in which the user saves the file containing 1,0 at the same time the script reads it.
% Flag to select the running mode
% Mode 0: start from the beginning
% Mode 1: resume the running
continue_my_script=1;
% if "Mode 1" has been selected, the "old" workspace is loaded and some
% variables are properly set
if(continue_my_script == 1)
load my_script_data
start_loop_1=i+1;
start_loop_2=1;
% if Mode 0 has been selected some variables are set to their default value
else
start_loop_1=1;
start_loop_2=1;
% counter to enable writing of the log file
cnt_log=0;
% counter to enable reading the "go / no go" input file
cnt_go=0;
end
% Definition of the condition for writing the log file (in this case, a
% certain number of iterations")
log_iter=13;
% Definition of the condition for reading the "go / no go" input file (in
% this case, a certain number of iterations")
go_nogo_iter=20;
% Starting point of the "real script"
for i=start_loop_1:100000
% Increment the log counter
cnt_log=cnt_log+1;
% if "log_iter" have been done, update the log file
if(cnt_log == log_iter)
cnt_log=0;
t=clock;
fp=fopen('my_script_log.log','wt');
fprintf(fp,'i= %d at %d %d %f\n',i,floor(t(4)),floor(t(5)),t(6));
fclose(fp);
end
% Another loop of the script
for j=start_loop_2:100000
a(i,j)=sqrt(i);
end
% Increment the "read input file" counter
cnt_go=cnt_go+1;
% if "go_nogo_iter" have been done, read the go_nogo input file
if(cnt_go == go_nogo_iter)
cnt_go=0;
fp1=fopen('my_script_go.log','rt');
go_nogo=fscanf(fp1,'%d');
fclose(fp1);
% If the user made the decision to stop the execution, save the workspace
% and exit; otherwise ... do noting, just continue running
if(go_nogo == 0)
save my_script_data
break;
end
end
end
Hope this helps.
Okay, just to rephrase what I said in the comments with inputs from other users who commented. If your script is a MATLAB script, (Not a function), all the variables will be accessible from the workspace as long as you did not explicitly called 'clear' in the script if the script is stopped. In the usual case, ctrl+c will terminate the running script. The MATLAB variables used in the script will still be accessible from the MATLAB Workspace.
I don't think there is anything you can do while the code is already running, unless you put some hooks in place beforehand. Some of these other suggestions are good for that. Here is another one that I like: say you are leaving for the night, but coming back the next day, so you want your code to run for 14 hours and then stop and be waiting for you with however much data it got to in that time.
start_time = now;
final_time = start_time + 10/86400; % datenums are in days in Matlab, so +14/24 for 14 hours
% alternative: final_time = datenum('12-Aug-2015 09:00:00');
while now < final_time
% do work
disp('Working...')
pause(1)
end
% potential clean up code to save results
disp('Clean up code.')

Alternatives to `clear(function_name)` to remove function from RAM?

As stated in MATLAB's FAQ,
1.3.3.1. Why, when I edit a function file in MATLAB, is the change not seen by MATLAB until everything is cleared or MATLAB is restarted?
When you write an M-file in MATLAB, you can either write a script or a
function. The difference is that a script is read from the disk and
parsed line by line each time it is called. A function is loaded into
RAM for execution. Because it is loaded into RAM, when you edit a
function, that change is not loaded into RAM until a call to the new
function is made.
To get MATLAB to recognize your edited function, type
clear functions to clear all functions, or
clear <function name> to clear just your function out of RAM.
This is a major pain when I'm developing a function & editing it repeatedly (I use an external editor most of the time). I was thinking of putting in a final line, at least during debug, like
clear(myfunc)
but I'm concerned about unwanted side effects. Does anyone know if there are any?
Further, I'd rather have a way to configure MATLAB so it doesn't automatically store called functions in RAM once the top-level function (i.e. the one called from the console) terminates. Is that even possible?
EDIT: I should mention that MATLAB's behavior is inconsistent. Sometimes my edits take effect once I save the m-file, other times they don't even if I'm editing with the MATLAB IDE editor window.
In all honesty MATLAB has a very powerful editor so you really should
be using it. It will make you life easier. (just an opinion)
Unless you are running the code by stepping through it no change to code will be run until the code is re-run (preferably with a cleared workspace).
clear(myfunc) will clear the variables created by that function in upto that point. You can add at the end of any function or script clear variableA variableB for all variables you want cleared at the end. This will give you control to only clear what you want. Once variables are cleared the only effect will be that if those variables are called again later in the code an error will occur since they no longer exist.
If your simply testing that particular function and want to save time by not calling inputs each time and want to clear the workspace and command window at the same time. You can add the following code just beneath the function definition.
If you leave the following code and call the function from another function or script, the code will be ignored as long as the inputs are available to it externally. Anything you add to the if statement will only occur when you call the function with no inputs doc nargin. You could add it to the top level function and you would simply press the run button or f5 without having to type in the command window to run the code.
function [ output1, output2 ] = blah( input1, input2 )
if nargin == 0
clc
clear all
%above two lines will clear the workspace and command window when you run
%the function
%define function inputs
%(optionally add the following to behave as if you inserted a breakpoint
%in the location just before the error occurred (great for debugging)
db stop if error
end
*you can also add a short-cut to snippets of code up in the top right of the MATLAB interface to clear the workspace etc when they are clicked.
Hackish* idea for this:
I'd rather have a way to configure MATLAB so it doesn't automatically store called functions in RAM once the top-level function (i.e. the one called from the console) terminates. Is that even possible?
* This is the sort of thing I might use, while advising others on why it is a bad idea, also probably uses undocumented (thus unreliable) things.
Specifically if your using an external editor I guess your going to have to click on the command window to run the function...
commandWindowHandle = ...
handle(com.mathworks.mde.desk.MLDesktop.getInstance.getClient('Command Window'...
.getComponent(0).getComponent(0).getComponent(0),'CallbackProperties');
commandWindowHandle.MouseClickedCallback = 'clear functions'
It doesn't clear the function definitions on exiting a function rather on clicking on the command window
note: the callback will not fire if a function is currently running
For a potentially more reliable but more wasteful version:
commandWindowHandle.KeyPressedCallback= 'clear functions'
will help* ensure definitions are clear, but is wasteful as every keystroke will run 'clear functions'... although after one keystroke this will be quicker as there will be no functions in memory!
* No guarantee I know there are ways in which this could fail... having at least 1 keystroke in the command window after the previous function call has finished would be advisable!
To disable these set the callback to empty string ''
commandWindowHandle.MouseClickedCallback = ''
commandWindowHandle.KeyPressedCallback= ''

How to stop a Matlab script but don’t kill the process? [duplicate]

This question already has answers here:
Stop and continue execution from debugger possible?
(6 answers)
Closed 8 years ago.
Strg+C stops and kills a Matlab script (at least sometimes). But is there a way to stop a Matlab, take a look at some variables and continue the calculation?
I am not talking about just setting a breakpoint. I want my script, let’s say run for couple hours come back to it hit some buttons that stops the calculations take a look at some variable and then continue the calculation.
I tried to find out if there is some shortcut key for this – I am quite sure there isn’t.
Now I was thinking about including an if-case that looks if a certain button was pressed by the user. If so there would be a useless k=0 line and a breakpoint on it. And if no one is pressing this button the loop would continue. But this is where my limited Matlab knowledge leaves me. I don’t know if there is a way to ask for a user-button press but don’t wait for a button press like in the function input. Also I just have a running script, I don’t have any GUI.
To drop to the command prompt you need the command keyboard and then type return when you have finished (you don't need a breakpoint). The tricky bit is how to trigger it. There a few options. The easiest is to open a figure window. The following code halts the process when any key is pressed.
keyDownListener=#(src,event) keyboard;
fig = figure;
drawnow
set(fig,'KeyPressFcn',keyDownListener)
for p=1:10000
%do some thing
end
You can modify this to test for a specific key since the keypress is contained within the event struct.
To use no figure gui at all its more of a problem. I'm not aware of a non blocking keyboard input method. A mex file the runs kbhit() in C might do it, but kbhit() is not standard C so it would only work on Windows. An easier option maybe to test for the presence of a file.
for p=1:100000
if exist(fullfile(pwd,'halt.tmp'),'file')
keyboard
end
%do something here
end
This drops to the debug console when halt.tmp is created in the current directory.
Other potential methods could involve using multiple threads to read 'input' (either the Parallel computer toolbox or undocumented Java code), or using http://psychtoolbox.org/ as mentioned by #bdecaf

Detect Keyboard Input Matlab

I have a simple question, although it's harder than it seems; I couldn't find the answer on the interwebs :O
I'm writing a script in Matlab. What I want to do is the following:
When I press the esc key, I want a helpdialogue to pop up, so my script pauses. (So when I press esc, I want to stop the whole script to run so that the car (which im writing the script for) stops driving)
How do I do this? How can I say to Matlab: When I press esc, do this...
Thanks for your time guys!
EDIT: It's no option to implement something which awaits the keypress. Im writing a script for a driving car. It just has to drive around basically, but when I press esc for example, it should stop driving. So the script just has to run, untill I press the esc key; then the script has to pause.
KeyPressFcn is good because it forces you to write event-driven code. Which is generally a good idea! However, if KeyPressFcn doesn't seem right for you, for example if you must keep running in a loop, and you just want to poll whether a key has been pressed, I found this solution buried in the matlab website:
get(gcf,'CurrentCharacter')
Then you could set this property to a blank, and poll it as required.
e.g:
finish=false;
set(gcf,'CurrentCharacter','#'); % set to a dummy character
while ~finish
% do things in loop...
% check for keys
k=get(gcf,'CurrentCharacter');
if k~='#' % has it changed from the dummy character?
set(gcf,'CurrentCharacter','#'); % reset the character
% now process the key as required
if k=='q', finish=true; end
end
end
This worked well for me in 2014b. The downside is that the graphics window needs to be focused to receive the key events.
In a matlab figure you can define a 'KeyPressFcn' that works similar to do what you ask.
If you are in the console you have to work around that matlab is single threaded. Basically you need to halt the program flow to check for key presses.
btw - also when you use 'KeyPressFcn' you will need to make some pauses so that Matlab will check if anything has happened.
btw2 - I should also add during this pauses Matlab will not only read your key presses - but also do some housekeeping such as redrawing its window and stuff.
I frequently ran into similar use cases and typically preferred to react to joystick buttons because of the more convenient interface provided by vrjoystick. However, I recently wrote a library that provides a similar interface for keyboard inputs.
% Pause on ESC
kb = HebiKeyboard();
while true
state = read(kb);
if state.ESC
% PAUSE DRIVING
else
% DRIVE CAR
end
end
It's non-blocking and doesn't require focus on any particular figure.
File Exchange: http://mathworks.com/matlabcentral/fileexchange/61306-hebirobotics-matlabinput
Github: https://github.com/HebiRobotics/MatlabInput
I had a related task once, and i did it with getkey form matlab file exchange.
Basicly you will want to have it listen for ascii 1B (27 decimal)
if getkey does not solve your problem you can still have a look at its code and maybe find the line that will do the trick for you.