How to edit property of figure saved in .fig file without displaying it - matlab

I want to edit a certain property of MATLAB figures saved as .fig (MATLAB's default format) files.
I create a lot of graphics-intensive figures in a script, so I choose not to display them by making the default figure invisible with set(0,'DefaultFigureVisible','off'). This sets the 'Visible' property of any new figure to 'off'. This way I can create, edit, save, etc., figures without the need to draw them, which can be taxing on CPU, GPU and their memories. I save the figures as .fig files using the saveas(handle,'filename.fig') command. This also saves the 'Visible' property, which is a problem when I do want to open the figure (e.g. by double-clicking the file in my Windows Explorer). It loads the figure, but it doesn't display it because its 'Visible' property is set to 'off'.
I want all .fig files to be saved with the property set to 'on', but how can I achieve this without displaying (= taxing) the figures? The moment I use set(handle,'Visible','on'), the figure is drawn.
So basically, I want to edit the file on a lower level than when it's loaded as a figure in MATLAB.
I think it could be done as follows, but I do not know exactly how to achieve it. One can load the .fig's data as if it were a .mat file using s=load('filename.fig','-mat');. This loads a structure s containing some fields that contain all the figure's data, properties, etc. Now, the figure handle must be found in this unkown structure and the 'Visible' property that goes along with the handle edited.
Can this be done without the figure being drawn?
I tried, but haven't succeeded, using fopen, fread and their friends.
Does anybody know how to do what I want to do?

I base my solution on the thread from the url posted by user4506754: http://www.mathworks.com/matlabcentral/newsreader/view_thread/306249
There, Jesse Hopkins posts (post 15) that you can edit a property 'ResizeFcn' to execute a function when MATLAB creates a figure. This doesn't work on my MATLAB installation, but lead me to look into the different functions you can attach to a figure in its properties. This page documents all figure properties: http://mathworks.com/help/matlab/ref/figure-properties.html. There I found the 'CreateFcn' property. Its description contains:
This property specifies a callback function to execute when MATLAB creates the figure. MATLAB initializes all figure property values before executing the CreateFcn callback.
It means that the figure is loaded with its properties, including the 'Visible' property being 'off' and then 'CreateFcn' is called.
Setting 'CreateFcn' to make the figure visible then solves my problem.
set(gcf,'CreateFcn','set(gcf,''Visible'',''on'')')
An example:
ezplot(#sin) % draw a simple figure containing a sine wave, title, etc.
set(gcf,'Visible','off','CreateFcn','set(gcf,''Visible'',''on'')' % this disables the figure and set the 'CreateFcn' property simultaneously
saveas(gcf,'sin.fig') % save the figure in the current folder as a .fig file
close % closes current figure
Now go to the current folder in your Explorer and double-click the sin.fig file. It makes MATLAB load it and, poof, the figure is drawn.
Solution found.
This doesn't edit the .fig file, as I originally asked (as a solution), but it is an alternative solution to the original problem. Now I can create and save figures without them being visible, but draw the figures the moment they're loaded by MATLAB.

Related

how to save figure of gui plot which will run on a computer that does not have matlab

I have made a Gui program that I compile to EXE application which lots csv file into graph data. I buit a save button but I do not know how save figure with different name each time cause (savefig anduisave both uses matlab program). I am posting my code below if anyoff you guys figure out how to save gui figue into image or anything that does require matlab to open. Last function is the callback function for save button.
function ma_Callback(hObject, eventdata, handles)
% i tried uisave but not possible to run computer without matlab cause mcr
% does not run uisave
% i tried copyopbj but since i did not put a name on my figure it did not
% work
%savefig
If you are trying to save a kind of image from your figure, then the best option which supports many aspects, is using print function.
I have already done this in a compiled app and it works perfect. Using print function you can set different file type(vector formats like *.svg are also supported), resolution(dpi), and so many others.
Although you can use print function directly on the figure, but I found that the best way (More Customization like removing or adding some objects and changing many options) is to follow this steps:
Create another figure with Visible='on' but a position that is out of screen with the same width and height of Main Figure.
normalized position = [-1, -1, ?, ?]. (Create this figure in start up and don't destroy it until your app exits, let call it Print Figure).
Copy your figure content (or the parts you are interested in) using copyobj to that figure (you may need to set Parent property of some key objects like panels to this new figure). They would look exactly as they look in the main figure, because they have the same properties. you can add or remove some objects in this step.
Change aspect ratio of "Print Figure" for a better output.
Print this figure with all options (file format, dpi, ...) you need. in my own GUI i allowed the user to change this settings with an input dialog.
In my app i used functions like winopen to show the output, and output directory to the user, when the print task was done. Print process takes some time, specially if dpi is huge, so it is also a good idea to inactivate buttons and show wait cursor.
Update:
a simple usage would be:
print(MainFigure, 'myFileName', '-dpng', '-r300')

Matlab 'load' figure objects from '.mat' file opens plot window

Why does MATLAB open a plot window when I load a .mat file that contains a figure inside an struct?
The problem that I am facing is that I have the output of an optimization algorithm as a collection of .mat files. Each .mat file contains the state of each generation of the algorithm in a form of a single struct. The state structure has (among other variables) a field of type matlab.ui.Figure. Now, whenever I try to load any of these files with the load command, a plot window opens automatically.
Is there any way to stop MATLAB from from opening this plot window?
I am using MATLAB 2015rb.
The reason that it is displaying a figure is because if you look closely at your state structure, there is a figure object stored in there. When you load this graphics object (or any object, really) from a file, MATLAB will reconstruct the object. The defined behavior for loading a figure (it's loadobj method) is to open the figure.
This is a recent issue because older versions of MATLAB stored graphics handles as simply a number and when loading a graphics handle from file, MATLAB had no way of knowing that it was supposed to be a figure so it would just parse it as a number and move on without displaying a new figure window.
Unfortunately since your figure handle is nested within a struct there is no easy way to not load it. Probably the easiest thing to do would be to just delete the figure object right after loading the file (since you have the handle already).
data = load('filename.mat', 'state');
delete(data.state.hFigure);
And if you really don't like the figure poping up even for a second, you can set the default figure Visible property to 'off' prior to loading and then reset it afterwards.
% Determine what the visibility was
prev = get(0, 'DefaultFigureVisible');
% Make it so figures don't appear
set(0, 'DefaultFigureVisible', 'off')
% Load data and delete the figure
data = load('filename.mat', 'state');
delete(state.hFigure);
% Reset the visibility
set(0, 'DefaultFigureVisible', prev)
Another potential solution (which would not require you to know where the figure handles are in your struct) is to overwrite the DefaultFigureCreateFcn to simply delete any figure that is created.
% After this point you can't create any figures or they will delete themselves
set(0, 'DefaultFigureCreateFcn', #(s,e)delete(s))
% Load your data (no figures!)
load('filename.mat', 'state')
% Allow figures to be created again
set(0, 'DefaultFigureCreateFcn', '')
In the future, to avoid this behavior, consider not saving any graphics handles within your .mat files. They are very large objects and MATLAB actually will issue a warning when saving one to a file as it is not recommended.
Warning: Figure is saved in test.mat. Saving graphics handle variables can cause the creation of very large files. To save graphics
figures, use savefig.

Save figures EPS from Matlab P file without display

My function calls code from other functions I did not write those but I know what they do. One of them is .p Matlab file with obfuscated content.
I am doing batch processing of a number of files. I want to write the figures directly to file without display. So I can go through them separately.
Any ideas on how to achieve this.
Thanks!
Script to save matlab figures to a specified directory
The above link works but I still want to avoid displaying the figures at all. Directly print to file. But the work around can simply close all open figures after that loop.
In your script, as soon as you create the figure, set its visibility to off.
For example:
figure(28732);
set(28732,'visible','off'); %Now the figure is not shown
You can now work with the figure, plot, save etc, without the visual clutter or system overhead of displaying it.
If you want ALL of your figures to start without visibility, you can set the default property, as follows:
set(0,'DefaultFigureVisible','off').
This will cause all generated figures to be generated without visibility. (Note, this will be very confusing is you forget that this property is set.)
You should still close the figure as soon as possible in the script, as a part of good memory management.

Saving GUI as .jpg in matlab

In matlab, I have created a GUI with several plots and edit boxes filled with text for an experiment with the bike. These plots and edit box values vary depending on the data I input (120 different sets). I was able to save the GUI as a figure with
saveas(handles.speedbike,fullfile(savename), 'fig');
Speedbike is the handle I gave to one of the plots and savename is the name that the figure is saved under, which changes with each set.
Now I also wish to save all the sepparate GUI's as jpegs, but using the same code as above, but with 'jpg' instead of 'fig' only saves a small corner of the figure as a jpeg, not the whole GUI.
Is there any function that I can use to correctly save a gui as a jpeg, or any way to open a .fig file, and then saving a copy of that as a jpeg.?
You need to use the handle of the whole figure for your GUI, instead of the handle of one of the plots. You probably also want to use print for saving to jpg.
Ive found satisfactory results with this:
hg=get(0,'Children');
saveas(hg,'.\gui.fig','fig');
optsave.Format='png';
hgexport(hg,'.\gui.png',optsave);
Why this do not work?. This normally do with normal figures, and failed with GUI's:
optsave.Format='meta';
hgexport(hg,'.\gui.wmf',optsave);

Dynamic grid of images in MATLAB

I'm working on creating a GUI in matlab using GUIDE. However, i'm not exactly sure how to do the following, and was looking for some tips/advice.
Problem
I want to open a directory and display all the images in that directory in the GUI interface when if it's selected. However, since I will never know exactly how many images there are I am not entirely sure how to do this in the GUI.
Essentially, I want to open the directory and all the images to be displayed in a grid on the GUI similar to that in iphoto.
Current code
Currently, I can open a directory fine, and get all the required information as follows:
directory = uigetdir(pwd, 'Directory Selector');
files = dir(fullfile(directory, '*.jpg'));
strcat(strcat(directory, '/') , files.name) %outputs each file's location
I'm just not sure how to translate this information into the GUI without writing numerous handles.axes1. I understand that since I know this info I could loop over them, but would I not have to create the axes to begin with?
You probably don't want to do this with individual controls - the reason is that MATLAB will have to render each and every one, which will be slow if the directory has a lot of images. Clearly, you can only display a certain number of images on screen at once. You would also have to write your own scrolling code (or some kind of pagination control).
If you have MATLAB > R2008, you can put images in uitable cells using HTML:
% Example for a control with a 'String' property
set(handles.myControl, 'String', '<html><b>Logo</b>: <img src="http://UndocumentedMatlab.com/images/logo_68x60.png"/></html>');
See also this post and this Undocumented MATLAB page.
A different option would be to use the Windows common controls ListView.
A simpler way of doing this would be to have a single image and a listbox of files; an example is here
You can add components to a GUI pprogrammatically. There's more information here.
Each new axes can be added with something like this:
ah = axes('Parent',hObject,'Position',[left bottom width height]);
where left, bottom, width and height define the size and position of the axes. You'll need to change the position for each axes you create and keep track of the axes handles.