matlab figure taking too long to open - matlab

I want to save a plot in .fig extension. I tried many ways but it takes too long to open (in fact it never opens sometimes after infinite wait time). I had to use Ctrl C in the command prompt to stop it.
Here are my commands to print a figure in fig format
saveas(h,[path FolderName FigureName, '.fig'])
where h is the handler. I used h at many places in the code file
(where the variables inputsAxis etc.., are defined basing on the where I need to plot. plot count is set to 10, inputsAxis = [1,2],SignalAxis = [3 4], VoterOutAxis -= 5 )
h(1) = subplot(plotCount,1,inputsAxis);
h(2) = subplot(plotCount,1,SignalAxis);
h(7) = subplot(plotCount,1,voterOutAxis);
h(5) = subplot(plotCount,1,FlagAxis);
h(6) = subplot(plotCount,1,MarginAxis);
h(9) = subplot(plotCount,1,flagAxis,'Color',[1 1 0]);
Also used
savefig([Path FolderName FigureName '.fig'])
I can print in the jpeg file but it is not as good as .fig for the simulation I am running.
I am not sure what I am missing here. It is more useful to me saving the figure in .fig format but when I do I can not open it by double clicking on it or by using openfig(filename) command.

Following our discussion in your comments section, my suggestion is to save your variables into a .mat file, which is very fast.
For example, if you want to save specific variable a, simply enter
a=3;
save('variables.mat', 'a');
clear all;
load('variables.mat');
Alternatively, if you simply want to save all variables into a .mat file, enter
save('allMyVariables.mat');
clear all;
load('allMyVariables.mat');
Please note that I wrote clear all to indicate that you may overwrite variables between save and load, or that you may even restart Matlab completely.
Check out http://www.mathworks.com/help/matlab/ref/save.html?refresh=true for a detailed explanation.
Cheers

Related

How to open desired figure by dialogue box in MATLAB

Is there any possible way to open the desired figures from a lot of plotted figures in MATLAB?
If it is possible with dialogue box then it will be perfect.
I have like 75 figures plotted after my code but I have closed the figures at end of loops as they are too much.
Is it possible to open just one figure by just entering values necessary for plotting figure in MATLAB at end of program?
One way to do this is the following:
1) You save the figures as .fig in a dedicated folder using the saveas command, e.g.:
saveas(gcf,['FileName_',num2str(idx),'.fig']);
where idx is the index associated with the figure number (so in 75 in the example you mentioned). For simplicity, I would save all of them in one folder.
2) You use inputdlg to create an input dialog box, where you type in the index you want. Then, you run uiopen(['FileName_',idxFromInput,'.fig']), which will display the figure. Note that the output from inputdlg is normally a string, so you don't need num2str here.
From Wikibooks: MATLAB Programming/Handle Graphics (emphasis mine):
Every time you close a figure, either by using the close function OR by hitting the 'X', you can no longer access the data, and
attempts to do so will result in an error. Closing a figure also
destroys all the handles to the axes and annotations that depended on
it.
This means that once you close your 75 figures, they are gone for good.
I would suggest saving all your figures to .fig file format, because this will allow you to open them later in MATLAB.
Take the following example:
x = linspace(0, 2*pi); % Sample data.
for i = 1:3 % Loop 3 times.
h = figure; % Create figure window and capture its handle.
plot(i*sin(x)); % Plot some data.
saveas(h, sprintf('fig%d.fig', i)); % Save figure to .fig file format.
close(h); % Delete the figure.
end
Now you can tell MATLAB to open one of the figures using the openfig function. For example, let's open the second figure fig2.fig. Go to the Command Window and type openfig('fig2') (including the .fig extension in the file name is optional).
>> openfig('fig2')
ans =
Figure (1) with properties:
Number: 1
Name: ''
Color: [0.9400 0.9400 0.9400]
Position: [520 371 560 420]
Units: 'pixels'
Show all properties

Fast way of exporting the same figure n-times

I am trying to put together an animation in matlab. For this i am showing pictures containing a description of whats currently happening in the animation. So i am writing out pictures of my figures and later on put these together to an avi file again using matlab. For the description parts to "show up" long enough i use a simple loop in which the current figure is saved n-times. Unfortunatelly this process, though matlab does not have to calculate anything new, is the slowest one.
As the loop i use the following (h_f being the figure handle):
for delay = 1:80
export_fig (h_f,['-r' num2str(resolution)], ['C:\Users\Folder\Name_', '_' num2str(7700+delay) '.png'])
end
I just want to ask if there is any faster way. right now it kind of feels like matlab replots the fig each time before exporting it. So is there a way of plotting the figure once and simultaneously export it n-times?
Thanks for the help :)
If they are all really identical, then you can just copy the first file into the subsequent files. Your time will be limited by the speed of your disk drive and the size of your image files.
% Define some of the flags as variables. This'll make it clearer
% what you're doing when you revisit the code in a year.
% Flag for the resolution
resFlag = sprintf('-r%u', resolutions);
% Base folder
folder = 'C:\Users\Folder\';
% First file number
startnum = 7701;
% This is the pattern all the filenames will use
nameToken = 'Name_%u.png';
% First filename
firstFile = fullfile(folder, sprintf(nameToken, startnum));
% Export the first file
export_fig(h_f, resFlag, firstFile);
numCopies = 80;
% Copy the file
for delay = 2:numCopies
% Make a new filename
currentFile = fullfile(folder, sprintf(nameToken, startnum + delay));
% Copy the first file into the current filename.
copyfile(firstFile, currentFile);
end

How to close one or all currently open Matlab (*.m) files from Matlab command prompt?

I found a solution on the web (see below, circa 2009) which does not work on my machine (Windows 7, Matlab R2013a):
Editor = com.mathworks.mlservices.MLEditorServices;
Editor.closeAll;
As you noticed, newer versions of Matlab do not return the same type of Java object for the editor.
The main editor service can still be accessed with the same command as before:
edtSvc = com.mathworks.mlservices.MLEditorServices ; %// get the main editor service ;
But this only return the handle of the service, not individual editor.
As answered by Daniel, you can close the full service from there, which will close all the editors at once. You can use one of the 2 methods available:
edtSvc.getEditorApplication.close ; %// Close all editor windows. Prompt to save if necessary.
edtSvc.getEditorApplication.closeNoPrompt ; %// Close all editor windows, WITHOUT SAVE!!
Now in this version, each file opened is actually an instance of an editor object. If you want control of individual editor tab/window, you can retrieve the list of the editor objects, then apply methods on them individually:
edtList = edtSvc.getEditorApplication.getOpenEditors.toArray ; %// get a list of all the opened editor
edtList =
java.lang.Object[]:
[com.mathworks.mde.editor.MatlabEditor]
[com.mathworks.mde.editor.MatlabEditor]
[com.mathworks.mde.editor.MatlabEditor]
This return a vector of com.mathworks.mde.editor.MatlabEditor object. (I have 3 opened file in my editor for this example).
From now on, each of these object controls an individual file. You could close a single file already but you need to know which index is the file you want to target. To know which one points to what, you can query the getLongName property:
>> edtList(1).getLongName
ans =
C:\TEMP\StackExchange\Editor_control.m
But if you will have to control individual files, I find it easier to build a structure with field names corresponding to the file names. This could be done this way:
for k=1:length(edtList) ;
[~, fname ]= fileparts( char( edtList(k).getLongName.toString ) ) ;
edt.( fname ) = edtList(k) ;
end
Now I have a structure with meaningful names (well, at least for me, your files and field names will be different of course):
>> edt
edt =
Bending_Movie_Time_Lapse: [1x1 com.mathworks.mde.editor.MatlabEditor]
Editor_control: [1x1 com.mathworks.mde.editor.MatlabEditor]
foldfunction_test: [1x1 com.mathworks.mde.editor.MatlabEditor]
So back to closing an individual file. This can be done easily with one of the same method than before:
edt.foldfunction_test.close %// close with prompt if necessary
edt.foldfunction_test.closeNoPrompt %// close immediately without save
Note that at this stage, you also have access to a nice list of methods and properties for your editor file. You can have a look at them by using the autocompletion (Tab key) of Matlab.
Example done on Matlab R2013a / Windows 7 64 bits
The following seems to work. I've tested in Matlab R2014b, Windows 7 64 bits.
Acccess the editor Java object.
Get the number of open documents, say D.
Programmatically make the editor the window in front.
Programmatically send ALT-F4 keystrokes D times to close all open files. Optionally, send also N keystrokes D times in case some file is not saved and you want to close it (i.e. reply "no" when the editor asks if you want to save it). If the file is already saved, sending an N causes no harm.
For step 1 I found inspiration in this post. For steps 2 and 3 I inspected the methods of the editor object until I found something interesting. For step 4 I took the procedure I used in this answer, which in turn was based on this information.
Code:
closeUnsaved = 1; %// 1 if you want to close even if documentds are not saved
%// Step 1:
desktop = com.mathworks.mde.desk.MLDesktop.getInstance;
jEditor = desktop.getGroupContainer('Editor').getTopLevelAncestor; %// editor object
%// Step 2:
D = jEditor.getGroup.getDocumentCount;
%// Step 3:
jEditor.requestFocus; %// make editor the window in front
%// Step 4:
robot = java.awt.Robot;
for n = 1:D
robot.keyPress (java.awt.event.KeyEvent.VK_ALT); %// press "ALT"
robot.keyPress (java.awt.event.KeyEvent.VK_F4); %// press "F4"
robot.keyRelease (java.awt.event.KeyEvent.VK_F4); %// release "F4"
robot.keyRelease (java.awt.event.KeyEvent.VK_ALT); %// release "ALT"
if closeUnsaved
robot.keyPress (java.awt.event.KeyEvent.VK_N); %// press "N"
robot.keyRelease (java.awt.event.KeyEvent.VK_N); %// release "N"
end
end

MATLAB: Permanently set "Text Update Function" for Data Cursor in figures

Problem: I use MATLAB for science, and I often need more than 4 significant digits. Every time I use Data Cursor in a figure's GUI, I need to manually right-click on the point, Select Text Update Function... or Edit Text Update Function..., and navigate to the folder where I saved the function whose callback prints more than 4 (e.g. 8) significant figures. This is annoying and there should be a way to automatically change this.
Ideal answer: I want this done permanently for all figures, e.g. in a function that changes default settings in my startup.m file.
Good enough answer: I want a wrapped function to which I give the figure handle and it fixes this for me.
I humbly await SO's infinite wisdom.
The permanent solution
would be, to edit the default_getDatatipText.m function.
You can find it in:
C:\...\MATLAB\R20xxx\toolbox\matlab\graphics\#graphics\#datacursor
There you will find the line:
DEFAULT_DIGITS = 4; % Display 4 digits of x,y position
Edit it as desired, you can't do much harm, but make a backup before if you want.
Alternative solution:
There is also the possibility of custom data tips: Tutorial at Matlab Central
It could finally look like this:
(additional text outside data-tips was post-processed)
And as you're talking about precision. The data-tip always snaps to the closest data-point. It doesn't show interpolated data at the clicked position.
The permanent answer given by thewaywewalk doesn't work anymore in R2015a, and probably later ones. So here I share my solution for both the temporary and permanent solution
Temporary solution (for a single figure):
The following function contains the update function as a nested function. Call datacursorextra to apply it to the current figure, or datacursorextra(fig) to apply it to some figure fig.
function datacursorextra(fig)
% Use current figure as default
if nargin<1
fig = gcf;
end
% Get the figure's datacursormode, and set the update function
h = datacursormode(fig);
set(h,'UpdateFcn',#myupdatefcn)
% The actual update function
function txt = myupdatefcn(~,event)
% Short-hand to write X, Y and if available Z, with 10 digit precision:
lbl = 'XYZ';
txt = arrayfun(#(s,g)sprintf('%s: %.10g',s,g), lbl(1:length(event.Position)), event.Position,'uniformoutput',false);
% If a DataIndex is available, show that also:
info = getCursorInfo(h);
if isfield(info,'DataIndex')
txt{end+1} = sprintf('Index: %d', info.DataIndex);
end
end
end
Permanent solution (apply to all figures by default):
I have not found a way to set a default UpdateFcn for the data cursor, but it is possible to add some code which will be called every time a new figure is created. Add the following line to your startup.m:
set(0,'defaultFigureCreateFcn',#(s,e)datacursorextra(s))
and make sure the datacursorextra function given above is available in your Matlab path.
#caspar's solution works very well.
You can also update the txt{} part of the solution with
if isfield(info,'DataIndex')
DataIndex = [info.DataIndex];
txt{end+1} = sprintf('Index: %d\n', DataIndex(1));
end
This will enable you to update the Index field when you have multiple pointers in the same figure.

How to check if a figure is opened and how to close it?

My m-file opens figures depending on parameters. Sometimes is one figure, sometimes it opens 2 figures.
If the user call the function, the figures appear. If he calls the function again, with other parameters, I'm clearing figures with clf before the new plots.
If the second call is set to draw only one figure, the second one (opened by the previous call) remain gray (because of the clf).
Is there any way to check if it is opened and close it?
close all
Will close all open figures.
You can use findobj() to find objects that may exist by specifying search parameters. For example:
figure('name','banana')
Creates a figure with the name banana.
close(findobj('type','figure','name','orange'))
Does nothing because there are no figures open with the name orange.
close(findobj('type','figure','name','banana'))
Closes the figure.
You can specify search parameters to meet your needs.
I'm a little unclear about what you mean by "open". Figures don't really have "open" or "closed" states. They either exist or they don't. The FIGURE command will return a handle to the figure it makes:
hFig = figure(...your arguments here...);
You can also get a figure handle from the FINDOBJ function, which will find all graphics objects matching the property values you pass to it:
hFig = findobj(...your property/value pairs here...);
You can get rid of a figure with either of these commands:
close(hFig);
delete(hFig);
You can check if a figure has been closed/deleted using the function ISHANDLE:
ishandle(hFig) %# Returns 'true' if the figure exists, 'false' if it doesn't
Figures can also be "visible" or "invisible". They have a 'Visible' property that you can get or set the value of:
get(hFig,'Visible') %# Returns 'on' or 'off'
set(hFig,'Visible','off') %# Makes a figure invisible, but it still
%# exists (i.e. it's not closed)
If you're wanting to check if a figure is minimized, that may be a little more difficult. I believe there are some files that may help you with that on the MathWorks File Exchange: here's one to check out.
In MATLAB, you can GET information on the 'root'. Figures are children of 'root' (handle of root is 0) they are the only children of the root.
http://www.mathworks.com/help/techdoc/creating_plots/f7-41259.html
Knowing this, you can try this code that looks for the children of root, and gives you a list.
>> close all
>> get(0,'children')
ans =
Empty matrix: 0-by-1
>> figure(1)
>> get(0,'children')
ans =
1
>> figure(3)
>> get(0,'children')
ans =
3
1
I think you will find this the most direct way to query what figures are open.
isempty(findobj('name','Your_Figure_Name'))
if the answer is 0, then your figure is open
If inside your method, you create a figure without a 'name':
function [] = myMethod()
myFigure = figure()
end
you won't be able to access myFigure handle the next time through. So:
function [] = myMethod()
if ishandle(myFigure) % will fault, cant find variable myFigure
close(myFigure) % will fault
delete(myFigure) % will fault
end
myFigure = figure()
end
gnvoice wasn't 100% clear when he says:
You can check if a figure has been closed/deleted using the function
ISHANDLE:
He means you can only check AFTER you have recovered the handle:
function [] = createMyFigure()
recoveredHandle = findobj('type','figure', 'Name', 'myFigureName')
close(recoveredHandle)
delete(recoveredHandle)
ishandle(recoveredHandle)
myFigure = figure('Name','myFigureName') % now create figure
end
To close figure there is the "close" function. I'm still looking one to check if a figure is open.
for f=1:numel(findobj('type','figure'))
close(figure(f));
end
clear('f')