figures pop up during code is running in matlab - matlab

I'm running a large code so I would like to ensure everything is correct when it starts to run. One thing I do is to plot some data to see if they make sense. I had several such plots (figure (1), figure (2) ...) and all of them are buried in different 'if' sentences. But I found only some of them pop up during the code is running, the others just don't show up until the code finished running. I have checked all the if statements are true.
Since my code is a little large I can't put it here. Can someone tell me the possible reasons that affect when figures pop up (during the code is running or after it's finished)? Thanks a lot!

You can use the drawnow function to update your figures while code is still running. If you want your figure window to "pop up" at any given time, you may also need to explicitly call figure(figNum).
Note that while it can be fun to watch your figures update in real time, you may incur a severe performance penalty by doing so. If you have long-running loops, you might consider only showing every N-th update, where N is 10, 100, 1000, or some other appropriate value:
for iter = 1:1e6
plot(x,y);
if ~mod(f0,1000); drawnow; end
end
If you are just interested in plotting right at the beginning as a sanity check, you might run the first iteration of your code outside of a for loop, and run drawnow to make sure it plots. Then enter into the for loop starting at the second iteration. The advantage over testing iter==1 is that you don't have to waste cycles on a conditional at every iteration.

Related

End line takes large portion of time in Matlab profiler [duplicate]

So, I've recently started using Matlab's built-in profiler on a regular basis, and I've noticed that while its usually great at showing which lines are taking up the most time, sometimes it'll tell me a large chunk of time is being used on the end statement of a for loop.
Now, seeing as such a line is just used for denoting the end of the loop, I can't imagine how it could use anything other than a trivial amount of processing.
I've seen a specific version of this question asked on matlab central, but a consensus didn't seem to be reached.
EDIT: Here's a minimal example of this problem:
for i =1:1000
x = 1;
x = [x 1];
% clear x;
end
Even if you uncomment the clear, the end line still takes up a lot of computation (about 20%), and the clear actually increases the absolute amount of computation performed by the end line.
When I've seen this in my code, it's been the deallocation of large temporaries created in the loop. Each new variable created in the loop is deallocated at the end.

Matlab GUI windowButtonMotionFcn Slow When No Action Taken

I have a MATLAB (r2016a) GUI with a windowButtonMotionFcn callback. Inside the callback is an if-elseif-else block that changes the cursor depending on which axes in the GUI the mouse is over. It runs very quickly when it encounters the cases when it needs to change something, but according to profiler, takes a significant amount of time on the "return" command.
Can anyone offer insight into a way to correct this? It seems to me if it's not executing any more code, it should be running more quickly when it is exiting the function (i.e. not getting hung up on a "return") than when it has more code to execute.
A basic outline of the code is as follows:
function mouseMove(handles)
xy = %Get cursor position
if %xy over axes1
set(gcf,'Pointer','crosshair')
elseif %xy over axes2
set(gcf,'Pointer','arrow')
else
return %Here is where MATLAB is spending a lot of time
end
%A lot of additional code for when the cursor is over axes1 or axes2.
end
This may be related to the fact that the end of a function often appears in the profiler as taking a lot of time. In general, the profiler is good for identifying inefficiencies in your code (functions that are called too many times, etc.) but really isn't well-suited to actually benchmarking code since JIT acceleration isn't enabled. For benchmarking, it's best to use timeit or some other function.
That being said, when I implement your same callback, I don't see any performance hit for the return statement
As #Ander pointed out, you should pay attention to the Calls column as it's possible that the number of times that return is called is simply more than the rest of the callback. The default coloration of a given line is based on the total time and not the time per call.

MATLAB command line output not following

There is something very simple that can be very upsetting occasionally.
I sometimes want to keep track of the outputs of an algorithm at each iteration, so within a for loop, I use disp command of MATLAB to output some information. However, although there is quite a bit of time between the calling of dispcommands, the MATLAB command window falls behind and I need to use the mouse to keep up with it manually. Do you know if there is any way to have it not fall behind?
Thanks,
It really shouldn't fall behind, but I could see this happening if the computations are intensive and the MATLAB JVM, which drives the GUI, does get the resources to update the command window.
The following command may be of help:
drawnow update % or just drawnow
According to the documenatation page, this "causes only user-interface objects to refresh, if needed". If that fails, try just drawnow with no arguments to see if it helps to flush the entire system event queue, including graphics updates.
If that doesn't work you could insert a pause(0.01) or something similar as a last resort.
It shouldn't fall behind if you don't use the mouse at all. However, I often use the waitbar for this purpose.
FEX also has several text & GUI progress bars.

How to get the iteration number of lsqnonlin

I am doing parameter estimation in matlab using lsqnonlin function.
In my work, I need to plot a graph to show the error in terms of lsqnonlin iteration. So, I need to know which iteration is running at each point of time in lsqnonlin. Could anybody help me how I can extract the iteration number while lsqnonlin is running?
Thanks,
You want to pass it an options parameter setting 'display' to either 'iter' or 'iter-detailed'
http://www.mathworks.com/help/optim/ug/lsqnonlin.html#f265106
Never used it myself, but looking at the help of lsqnonlin, it seems that there is an option to set a custom output function, which gets called during every iteration of the solver. Looking at the specification, it seems that the values optimValues.iteration and optimValues.fval get passed into the function, which is probably the things you are interested in.
You should thus define your own function with the right signature, and depending on your wishes, this function prints it on the command line, makes a plot, saves the intermediate results in a vector, etc. Finally, you need to pass this function as a function handle to the solver: lsqnonlin(..., 'OutputFcn', #your_outputfun).
The simple way to do this would be:
Start with a low number of (maximum) iterations
Get the result
Increase the number of iterations
Get the result
If the maximum iterations is used Go to step 3
This is what I would recommend in most cases when performance is not a big issue.
However, if you cannot afford to do it like this, try edit lsqnonlin and go digging untill you find the point where the number of iterations is found. Then change the function to make sure you store the results you need at that point. (don't forget to change it back afterwards).
The good news is that all relevant files seem to be editable, the bad news is that it is not so clear where you can find the current number of iterations. A quick search led me to fminbnd, but I did not manage to confirm that this is actually used by lsqnonlin.

Disable plots in Matlab

I have some programs written in Matlab that I need to run several times for some reasons (debugging, testing with different input, etc...)
But, there are a lot's of graphs that are plotted by the programs and its various functions such that everytime I run the program, I have to wait for all the graphs to be displayed, which is very annoying and time consuming (especially when you are working with a small laptop).
After the program is executed, I close them with a close all.
So my question is:
Is there a way to disable all plots/figures/graphs in Matlab? either in the options, or by executing a certain code like disable plot and enable plot to ensure that no figures are being displayed.
I know that I can just browse the code and comment the plotting part, but I don't want to forget to uncomment.
Try some combination of the two commands:
set(gcf,'Visible','off') % turns current figure "off"
set(0,'DefaultFigureVisible','off'); % all subsequent figures "off"
The second one, if you put it near the beginning of your program, might do the trick for you. Of course, it is still creating the plots, which might be undesirable for computation time and/or RAM issues.
This is a classic reason to avoid Matlab when one can. It fosters bad programming design. To solve this problem correctly, you should create something that lets you "flip a switch" at the highest level of your program and control whether plots show or do not show. Perhaps it even has gradations of the show/don't show option so you can select different types of plots that do/do not show depending on what diagnostics you are running.
Ideally, you'd want this "flip a switch" creation to be a class that has access to visibility and plot functions of other objects. But because interactive object-orientation is so cumbersome in Matlab, it's often not worth the effort to develop such a solution, and most people don't think about this design aspect from the outset of their project.
Matlab would encourage someone to solve this by making flag variables like "isPlotVisible" or something, and creating functions that always accept such flags. I agree this is a bad design.
You could run matlab from the command line with:
matlab -nojvm
but then you don't get the GUI at all. Alternatively, you could write a file 'plot.m':
function h = plot(varargin)
h = [];
end
which doesn't do anything. If this is in the working directory (or somewhere else near the top of the path), then plot will call your function instead of the 'real' plot. You'd need to do the same from any other graphing functions you call.
The closest way I know of 'turning off plotting' would be a folder of such functions that you can add to the path to disable plotting, and remove to enable.
The previous methods are fine, but an easy and good habit to take is to use a "on/off parameter". So basically, at the beginning of your code, you can add something like:
DisplayFigure = 1; %1 = display, 0 = no display
After that, add "if DisplayFigure == 1 ... end" for all your plotting related commands, where the commands should be inside the if statement (the ... above). Hence you won't even compute the plots, which will save you a lot of time and memory. You just have to change the value of the variable "DisplayFigure" to plot or not the figures.