# Reproducing figures4

Posted by Michael Katz,

I’m taking a break this week from MATLAB R2010a features to show you a feature that’s been a part of MATLAB for years: generating MATLAB code from a figure. Last week I had the opportunity to visit some of our customers and observe what they do with MATLAB. I was surprised by the amount of effort one person spent on plotting and setting up the figures for series of data. His data sets represented different runs of repeated experiments, and as you can imagine, the figures all looked pretty similar. We suggested that he could save time by writing a function that took in a set of data and created and plot, that way he would only have to write and debug the various commands (such as plot, legend, axis, colormap, etc.) once.

The workflow I suggested to that user is as follows: (A) plot some data, (B) spiffy up the plot from the command line, (C) save those commands to a function file, (D) repeat on additional sets of data. I further suggested that step “C” could be sped up using code generation from the figure. Every figure has a “Generate M-File” command under it’s File menu. This command takes the Handle Graphics objects in the figure and recreates them in a function, where all you have to do is pass in the plot data. What I like about this feature is that the generated function is readable and can teach you about new properties of plot objects.

Here is an example of how it works, using the Scatter Plot from the graf2d demo:

load count.dat
scatter(count(:,1),count(:,2),'r*')
xlabel('Number of Cars on Street A');
ylabel('Number of Cars on Street B');

This code generates the following scatter plot:

From the figure’s “File -> Generate M-File” menu item we get the following function created in the editor:

function createfigure(X1, Y1, S1, C1)
%CREATEFIGURE(X1,Y1,S1,C1)
%  X1:  scatter x
%  Y1:  scatter y
%  S1:  scatter s
%  C1:  scatter c

%  Auto-generated by MATLAB on 16-Apr-2010 11:07:47

% Create figure
figure;

% polar currently does not support code generation, enter 'doc polar' for correct input syntax

% polar(...);

% Create scatter
scatter(X1,Y1,S1,C1,'Marker','*');

% Create xlabel
xlabel('Number of Cars on Street A');

% Create ylabel
ylabel('Number of Cars on Street B');

The quality and re-usefulness of the generated function will depend on the data, as well as the functions used to create the original plot. The generate file command uses low-level objects and basic plot types, so if the original plot was generated by a function that performs a lot of set up or massaging of data, there may be a decent amount of set-up you’ll have to perform in order to use the generated function. For example, in original code from graf2d the plot was performed by the 3-input form of scatter and our generated file uses the 4-input form, whose inputs we have to supply when calling generated createfigure like so:

createfigure(count(:,1),count(:,2),40,'r')

To get back my original plot, I had to intuit what the appropriate inputs need to be. In my simple example, I no longer need to supply the axes labels, but now have to define the marker size (input 3, “40″), and while the marker type, “*,” is taken care of, I still have to tell it “r” (4th input) to make it red. Using a different type of plot could mean that there are fewer things to specify, but they will still likely be different than the original set of inputs.

I hope you can imagine that with a more complicated figure with subplots, multiple titles and legends, etc that this feature could save a bit of work. Sometimes I use this feature in the same way I use GUIDE: I use the interactive mode (Plot Tools) to get the figure how I want it, generate the code, and then copy the appropriate sections to my own hand-written file that is more readable.

## 4 CommentsOldest to Newest

While the generated m-code is readable, I find that saving figures as a *.fig file is more reliable in preserving all aspects of the figure (inc. controls and axes).

As the example that you have provided above shows, polar plots are not currently supported and there are other quirks. Sometimes when I run a generated m-file, I get a run-time error (exception) – I never run into such problems with fig files.

Under the hood, a FIG file is really a simple MAT file that contains all the figure’s properties in a hierarchical structure. It is therefore slightly disappointing that Matlab doesn’t simply recursively loop over the structure’s elements when generating m-files.

I only use the feature “Generate M-file…” after opening plot tools (from an existing figure of course)
It is so easy to change a font , a colour or … whatever from plottols w/o knowing the exact parameter (fontsize, fontcolor…)
But like most of matlab developers , you are quickly limited:
For example , try to generate code from the example in PIE function (already sent last year to French Matlab support):


x = [1 3 0.5 2.5 2];
explode = [0 1 0 0 0];
pie(x,explode)


W/O link, I definetely like the R2010a.
How many customers have reported the error ??? Undefined function or method ‘mikehowareyou’ for input arguments of type ‘double’.
I know that there is a technical note about this common message, but I would prefer a message which would say “Check that ‘mikehowareyou’ is on your path.
With R2010a, a simple right click on any folder allow you to update MATLAB path (no need to know addpath, pathtool , File-> Set Path) …wow great !!

Jason G replied on : 3 of 4

I have to say that “Generate M-file” is one of the most disappointing Matlab commands because it has the opportunity to be so great but falls woefully short. This could be a stellar, useful option to create real m-code that would reproduce the plot exactly when called from the command line and then would allow tinkering with the plot style by editing the m-file directly, or would allow easy regeneration of the plot style with new data. But instead, it lacks potency and is difficult to use by Mike from Mathworks’ own admission. How about starting by saving all of the handlegraphics settings?

The purpose of any command in Matlab should be to save time and/or complexity. Please make “Generate M-file” live up to its potential in your next revision! I am a big Matlab fan (since 1994)

Mike replied on : 4 of 4

@Jason,

Thanks for those comments. We’re working on a whole suite of figure functionality that will replace the current Generate M-code functionality. However although it is seemingly underpowered by its name, there are a few workflows where this is useful, such as the one I highlighted or @Aurélien mentioned.

These postings are the author's and don't necessarily represent the opinions of MathWorks.