Stopping/pausing execution in Matlab to check the value of the variables while running [duplicate] - matlab

This question already has answers here:
Stop and continue execution from debugger possible?
(6 answers)
Closed 6 years ago.
I am trying to write a program in Matlab which is quite large and I want to stop or pause the execution to see what my variables values are.

I want to stop or pause the execution to see what my variables are.
One alternative is to use keyboard:
keyboard pauses execution of a running program and gives control to
the keyboard. Place the keyboard function in a program at the location
where you want MATLAB® to pause. When the program pauses, the prompt
in the Command Window changes to K>>, indicating that MATLAB is in
debug mode. You then can view or change the values of variables to see
if the new values produce expected results. The keyboard function is
useful for debugging your functions.
To continue executing your function, type dbcont, or type dbquit to quit the debug mode.
If you want to view the variables after a given number of iterations you can insert if ii = stop_point; keyboard; where ii is the iterator of the loop.
Another option is:
Use dbstop. This is shown with an example from the documentation:
Set a breakpoint to stop when n >= 4, and run the code.
dbstop in myprogram at 4 if n>=4
myprogram
Yet another option is to manually insert breakpoints in the MATLAB editor. Click on the left side of the code to insert breakpoints (indicated by a red dot). Now you can view the variable by hovering the mouse over the variable names in the editor
Have a look at this very relevant link to get more information.
Note, the following paragraph is a direct copy of chappjc's answer here. Please upvote his/her answer if you like this approach!
With the release of R2016a, you can just hit the Pause button in the code editor and it will halt right away.
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:

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.

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

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.

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

Can you pause MATLAB? [duplicate]

This question already has answers here:
Stop and continue execution from debugger possible?
(6 answers)
Closed 6 years ago.
In MATLAB, I'm running some code which takes a while to run. I'd like to pause the code to check on some variable values. Is there a way I can do this without having to re-run the code from the beginning? I don't want to terminate the program; just pause it.
You can halt execution and give a command prompt in two ways of which I am aware:
Putting keyboard in your code where you want to stop.
Setting a breakpoint.
You can resume and stop execution with dbcont and dbquit, respectively. To step forward, use dbstep. dbstack lets you see where you are. There are many more commands. The help page for any of these will give you other suggestions.
As Dennis Jaheruddin has pointed out, dbstop also has several useful features worth trying. In particular is the ability to set conditional and global (any line meeting a criterion) breakpoints via the dbstop if syntax. For example, dbstop if error will break to a debugging command prompt on any error. One suggestion he made, which I now do, is to put dbstop if error into startup.m so that this behavior will be default when you start MATLAB. You may need to create this file in a userpath folder; edit(fullfile(regexp(userpath,'^[^;]*','match','once'),'startup.m')).
One way to achieve what you're looking for would be to use code sections (also known as code cells), where you divide your code into sections divided by lines with two percent signs (%%).
Then, in the editor, you can press ctrl+enter to execute the current code section, and ctrl+up/down to navigate between sections.
Well there is the pause command, but then you cannot check for the variable contents in the workspace because the program is running.
What you probably want is to set a breakpoint (See the Debug menu / key F12).
At a breakpoint matlab pauses the program and enters debugging mode in which you can see and edit the variables. Once finished, you can resume the program where it was paused.
I'm not sure about Windows users but if you're running Linux you can start Matlab in a terminal using
matlab -nodesktop
then once Matlab has started, cd to your project directory and start your Matlab script. Now whenever you want to pause execution you can use ctrl-Z. Then to resume type fg. I hope this helps.

(matlab)implement "Evaluate or Open Code You Select" in everywhere? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you retrieve the selected text in MATLAB?
I want to implement and add some features to the function "Evaluate Selections", where you can highlight code and then "Evaluate Selections" by right click your mouse (or F9).
In the editor environment, this is how it is done:
editorObject = matlab.desktop.editor.getActive;
eval([editorObject.SelectedText ';']);
How can I implement this from the command line window, or the help window?
EDIT:
Maybe I didn't express my question clearly.
Imagining that we already have this function called eva_select(), I can use function this way:
I wrap the function as the Shortcuts button.
Use mouse to select a variable at command line window, maybe I entered before, say var_a
Then I click that Shortcuts button, the text which I selected before will be executed. This is exactly as press F9 key or choose right mouse menu -- "Evaluate Selections".
But if we really have that function, we can do more! We can modified eva_select() to eva_select_size(), in this way, we can select a variable, say var_a at command line window or help window, click eva_select_size() shortcuts button, then, we will get size(var_a) at command line window!
EDIT:
Thanks, I can retrieve the text in the command window, but I can't do the same thing in the help window, is it possible to do that?
The command window, like other GUI components in the MATLAB desktop, is Java-based. Therefore it can be accessed programmatically, but it is completely undocumented and its use is not officially supported.
Exploring around, here is a solution that seems to work in both R2012a and R2012b. It involves obtaining a handle to the underlying JTextArea of the command window, which is used to get the selected text (to evaluate size of selected variable name)
Create a shortcut with the following code:
x = com.mathworks.mde.cmdwin.XCmdWndView.getInstance();
s = char(x.getSelectedText());
if isvarname(s) && exist(s,'var')
eval( sprintf('size(%s)',s) );
end
Next highlight a variable name in the command window and execute the shortcut. The size will be immediately printed as shown in the screenshot below:
It is not very nice as it is an external solution, but this is how it could work:
Assuming you are in the command window and want to evaluate size(var_a) by selecting it, you can probably do this with a keyboard macro. Defind the appropriate function of var_a
f(x) = eval('size(' x ')'
%This could be done in the macro, but nicer to do it here for easy editing.
Then make sure your macro does this:
Copy 'var_a'
Turn it into 'f(var_a)'
Paste the result
Hit enter
Like i said, it's not pretty, but it should do the trick.