File Exchange

image thumbnail

matlabfrag

version 1.26 (732 KB) by

A matlab figure to .eps and .tex file exporter, similar to LaPrint

4.90909
42 Ratings

26 Downloads

Updated

View License

matlabfrag is a function which exports a Matlab figure to .eps and .tex files for use in LaTeX/pdfLaTeX/LyX. It is inspired by LaPrint, but is intended to be more WYSIWYG, by respecting figure handles better.

Some of the advantages of matlabfrag compared to LaPrint are:
- Much more emphasis on WYSIWYG.
- Handles figures that need the OpenGL or Z-Buffer renderers.
- Text objects are sized correctly (such as with a legend).
- Tick labels are handled better.
- Reduced number of options (which could also be viewed as a disadvantage).
- A great user manual ;-)

To include the figures in LaTeX, pdfLaTeX and LyX I recommend the pstool package. More information can be found in the User Guide.

Please email any bug reports to me (see my account for more details). I'm unlikely to notice any bug reports posted in the comments.

This is version 0.6.16 of matlabfrag, uploaded 04-Apr-2010.
- Fixed a bug that occurred when a figure wasn't frontmost.

Comments and Ratings (78)

Works great with 2016a! For exponents that don't display or return an error in TeX, just open the TeX file generated and put any exponential terms in math mode, e.g., \psfrag{000}[ct][ct]{\matlabtextC $10^{-2}$}%. The only issue I've run into is with the legend, but I'll give legendflex a try.

Umut

Umut (view profile)

@Christian, 19 Sep 2016, I am trying the legenflex script as you suggested but then the legend text is written on the border or the legend box. Did you experience a problem like this also, or do you know a fix for this?

Fei Lu

Fei Lu (view profile)

MatAtWork

Christian

I do not know about the opengl-issue and Lucas' solution does nothing good to me, but I found a workaround for the legend-problem: Using the legendflex.m function found here:
https://de.mathworks.com/matlabcentral/fileexchange/31092-legendflex-m--a-more-flexible--customizable-legend
Does the trick for me. It is intended for more flexible legends, but one can also use it for basic legends. Note the slightly different syntax, though

820408

820408 (view profile)

I am using matlabfrag(.) for the first time. Right now I have Matlab2015b version. ex02.m isn't working as my xlabel is "should not see this text" instead of "Plays nice with Latex".

Lucas

Lucas (view profile)

@Thomas, I was able to ``repair'' the code and now the 'opengl' is working on MATLAB R2015b, on my Mac.

I just added the following, after line 255, from Mfile matlabfrag.m:

drawnow;
print(p.Results.handle,'-depsc2','-loose',dpiswitch,'-opengl',FileName);
FileWait( [FileName,'.eps'] );

It should work after a save.

Best!

Lucas.

Thomas

Thomas (view profile)

It seems that Zebb Prime, the file's author, is unlikely to make any changes to the file (no edits in nearly 6 years). Would anyone be willing to fork this really excellent utility to an updated version, which is compatible with the graphics-update introduced after v2014b (e.g. resolve legend-issues)?
It would be unfortunate to see the best export-utility in Matlab die out because it is not compatible with new versions.

Thanks for the nice utility. One problem I had was that the output .tex has a line break in it, which adds a spurious space to my figure. I was able to fix this by adding a '%%' to the end of the string at line 287 ("writeOutNegXTick = ...").

Peter

Peter (view profile)

Conerning TickLabels: Apparently, MATALB saves strings of TickLabels as individual characters in the eps file (instead of e.g. '001', '0', '0', '1' is saved). A quick workaround is the following:
matlabfrag.m line 69: change to
REPLACEMENT_FORMAT = '%c'; %single character
matlabfrag.m line 117: change to
StringCounter = 65; % char 'A'

Alexander B

Same problem with Matlab R2015b... please make an update of matlabfrag :(

aacred

aacred (view profile)

Please could you address the compatibility issues with Matlab 2014b. This is incredibly useful code, but since updating Matlab can no longer use it.

Octopode

I have the same issue than Laura and Thomas regarding the legend. Any idea how to fix this?

Norman

Norman (view profile)

Matlabfrag combined with my Matlab (2007b) throws error in Latex, because Fontsize is given in exponential style, e.g.(xxe+001).
The error is that using the format conversion character %d (which means integer) does not work when used with non-integer numbers (at least in my version of matlab). Example:

>>fprintf(2,['Test %d' char(10)],pi)
3.141593e+000

Maybe the reason is that my Matlab is configured to display floating point numbers as above mentioned.

Nevertheless, for everybody who is affected by this error (line #349 in version 1.26):

fprintf(fid,['\n%%\n\\providecommand\\%s%s{\\color[rgb]{%.3f,%.3f,'...
'%.3f}\\fontsize{%d}{%d}%s%s%s\\selectfont\\strut}%%'],FontStylePrefix,...
char(FontStyleId),CurrentColour(1),CurrentColour(2),...
CurrentColour(3),CurrentFontSize,CurrentFontSize,Angle,Weight,Fixed);

The entry CurrentFontSize must just be changed to round(CurrentFontSize) (for example) to fix this.

Carlos

Carlos (view profile)

Matlabfrag is an excellent tool. I recently came up with a problem using opengl renderer: for instance, if I try to run "ex14.m" it generates an empty "ex14.eps" file. The problem happens when running line 1026:

fh = fopen([filename,'.eps'],'w');

The already created file "ex14.eps" with 2402KB is changed to an empty file. If I use

matlabfrag('graphics/ex14','renderer','painters','dpi',720);

instead of

matlabfrag('graphics/ex14','renderer','opengl','dpi',720);

everything works well. However, I'm interested in use opengl.

I'm using matlabfrag version v0.6.16 04-Apr-2010 and Matlab2015a.

Carlos

Carlos (view profile)

Thomas

Thomas (view profile)

I would repeat Laura's comment regarding the compatability with Matlab v. 2014b. Is there any way this excellent code could be updated to work with the most recent version?

Laura

Laura (view profile)

Since updating to Matlab 2014b; my legends are no longer typeset correctly by matlabfrag, because matlab introduced the "legend" object class and the labels are therefore no longer recognised as text objects. The text in the legend is stored in a multi-line cell, which matlabfrag can't handle. Does anyone have a solution for this?

Pablo

Pablo (view profile)

Charlie Hogg

Does anyone have any ideas on this exponent problem?

My guess is that matlab includes the exponents as a different kind of child of the plot object than other text, which causes trouble for matlabfrag. The axis exponents are difficult to access within matlab too.

Charlie Hogg

I have used this tool for ages and I think it's great.

I have one problem occasionally. When I try to plot a color bar which has an exponent (e.g. 10^-3), the exponent is not recognised in latex and the tag (e.g. 000) comes through.

Has anyone had this problem and found a work around? The tex file seems to be created ok, but the tag (000) in the eps file is not picked up.

My work around is to multiply the colour legend by the exponent and then add the exponent manually - not ideal.

Thanks,
Charlie

V_oron

V_oron (view profile)

Marko Budisic

I've been using this great tool for years, so thank you for making it.

However, I've just spotted a (possible) bug. When colorbar is displayed where number of color levels is relatively small, e.g., 5, matlabfrag-generated EPS will have a smooth color interpolation between those values.

For example, an empty plot, with just a colorbar:

colormap(jet(5)); colorbar

in Matlab figure looks as expected (five discrete color levels from jet map), yet in EPS the figure has a much larger number of levels, looking more like

colormap(jet(32)); colorbar

Additionally, the end colors in EPS range from light blue to orange, instead of purplish-blue to deep red (as in Matlab).

Is there an easy fix for this?

Ashley

Ashley (view profile)

Gah, I edited the code to get it to do what I want, but now the background boxes are too big, rather than too small.

Ashley

Ashley (view profile)

Thanks for this, the tool produces some great looking figures!

I just have one problem, related to text with a background color. The text is replaced by key values (for psfrag) before output, so the background color is much smaller than the eventual text. Is there any way around this? Maybe padding key values with zeros so they are the same length (in characters) as the original text?

Octopode

Hi. Nice tool, thanks.
I have trouble with multiple 3D axes, and the "OpenGL" renderer set in matlabfrag. With more than 1 axis, any other axes are ignored, while the text around it is accounted for.
See the sample :
http://s24.postimg.org/ogr9myeut/multi_axes_Open_Gl.png

There is not problem with the other renderer, all axes show up.
Any idea how to fix this ? I do need OpenGL renderer.

Stepan Kucera

a patch for a bug - add/replace lines marked by % <<<<

VAlign = get(handle,'VerticalAlignment');
switch VAlign
case {'baseline'} % <<<<
valign = 'B'; % <<<< this case must be distinguished in accordance with psfrag rendering in latex
case {'bottom','base'} % <<<<
valign = 'b';
case {'top','cap'}
valign = 't';
case {'middle'}
valign = 'c';
otherwise
warning('matlabfrag:UnknownVertAlign',...
'Unknown text vertical alignment for "%s", defaulting to bottom',string);
valign = 'l';
end

Charlie

Charlie

Hi Zebb,

Thanks very much for the quick response.

crop=preview did fix it for me. Some of the legends overshoot the figures, but I imagine this is why I should install pdfcrop. I'll summon the courage to install perl if I need to.

I was also making another mistake with my own figures which returned the same error. I was using the tex interpreter. Commands like \zeta were getting left in the labels and causing latex to return the errors.

Thanks again.

Zebb Prime

Zebb Prime (view profile)

Hi Charlie,

This sounds like a problem with pdfcrop. You should be able to fix it by changing:

crop=pdfcrop

to

crop=preview

in the latex file. Otherwise, to get pdfcrop working, you will need to make sure it is installed in Miktex (via the Package Manager), then make sure you have a working Perl installation (e.g. Activeperl).

Regards,
Zebb

Charlie

This package looks great.

Unfortunately, I cannot get the package to run smoothly.

When I run the (very helpful) test package, I can only get the figures to appear if I run using the latex>ps route.

If I run pdflatex, only figures 7 and 8 are succesfully included in the document. The other figures have a red box which reads "An error occured processing graphic ...". The log file is long, but I can't find in it what the problem seems to be.

I've looked around the web for a couple of hours. There is an error in pstool reported here http://tex.stackexchange.com/questions/60084/pstool-pdflatex-not-getting-pstool-to-work-latex-error-file-not-found, but I have the corrected update of pstools. I've checked that I have the -shell-escape option working correctly. Also, I can get laprint to work with my pdflatex setup (although I have to alter the tex document slightly).

Does anyone have any suggestions of what I might be doing wrong?

Many thanks in advance.

I am using TexnicCenter 2.0 with Miktex 2.9, matlabfrag v0.6.16 and pstool v1.5a.

Lishuai

I met a conflict when using \IEEEoverridecommandlockouts

Hi Zebb,

I have generated all the eps figures and .tex files from matlab. But when i import the figures to my paper, all the lables on the x-axises are shifted to the right. The reason is due to I included \IEEEoverridecommandlockouts

in the main .tex file to creat the paper. Why this conflict appear?

Best regards,
Lishuai

kevin

kevin (view profile)

Nick

Nick (view profile)

Fantastic little gem of a script!

However I've had some issues with labels not being coded in the PostScript file properly.. The number key and label is in the .tex file.. But appears to be missing it's partner in the postscipt.. And hence appears as '001' etc when processed. Has any one overcome this issue?

Cheers,
Nick.

Tobias

Tobias (view profile)

This is a great tool! Best way to prepare matlab figures for LaTeX. Thank you!

Bernhard

Great work.

Only question is, why is it not naturally included in MATLAB?

Peter

Peter (view profile)

Thank you for an extremely useful tool.

To avoid warning messages, when supplying absolute paths, you might want to replace

if ~exist(['./',pathstr],'dir')

with

if ~exist(['./',pathstr],'dir') && ~exist(pathstr,'dir')

or something...

Koen

Koen (view profile)

Great script!

I found that a cause of axis scaling not being handled properly can be the use of axis() with either of the arguments inf or -inf. This messes up the placement of the replacement string. Replacing the values with a numerical value fixes the problem.

Hopefully someone will find this useful!
Koen

Hey Zebb,
I am a huge fan of LaTeX (used it to write my dissertation), and had I known of your function -- well, my life would have been a bit different. Very nice work.
Two comments:
1) The sortrows function in MatLab 2011a has been changed to perform a check on input array with ismatrix, and as such, throws an error within matlabfrag. I made a simple fix by changing the sortrows to sort as below (lines 262 to 282), however, I didn't check if this changes the sort logic:
% Sort by text size first
%[Y,I] = sortrows(cell2mat( PsfragCmds(:,4)))
[Y,I] = sort( cell2mat( PsfragCmds(:,4) ) ); %#ok<*ASGLU> Required for backward compatibility
PsfragCmds = PsfragCmds(I,:);
% Now sort by colour
[Y,I] = sortrows( cell2mat( PsfragCmds(:,5) ), [3 2 1] );
PsfragCmds = PsfragCmds(I,:);
% Now sort by font angle
[Y,I] = sort( cell2mat( PsfragCmds(:,6) ) );
PsfragCmds = PsfragCmds(I,:);
% Now sort by font weight
[Y,I] = sort( cell2mat( PsfragCmds(:,7) ) );
PsfragCmds = PsfragCmds(I,:);
% Now sort by whether it is 'fixed width'
[Y,I] = sort( cell2mat( PsfragCmds(:,8) ) );
PsfragCmds = PsfragCmds(I,:);
% Now sort by label type
[Y,I] = sort( PsfragCmds(:,9) );
PsfragCmds = PsfragCmds(I,:);
clear Y
2) How does matlabfrag handle background color in text annotations? I am trying to publish a few statistics and an equation on the plot, but haven't had much luck.

Thank you again, it's really an incredible function,
Cheers,
Nicholaus

Benjamin

Frederick

Thanks for that Zebb!

Zebb Prime

Zebb Prime (view profile)

Herwig: The use of single dash or double dash with the --shell-escape option depends upon your LaTeX distribution. On my system, both variants work.

Fredrick: That is a pstool question, not a matlabfrag question. If you read the pstool documentation you'll see that you can specify \includegraphics options as options to \psfragfig, i.e.

\psfragfig[width=10cm]{...}

That said, the workflow I designed matlabfrag for is to resize the figure in matlab first, so as to prevent things like text running on top of tick labels, etc.

As for your other problem, I don't know what the problem it. Try updating your version of pstool.

Frederick

How do you resize a figure in pdftex using the command \psfragfig{S10MeanPeakt111}? And for me I cannot specify a eps/tex combination that is not in the same directory for some reason.

E.

E. (view profile)

In the above replace get(0,'ScreenSize') by get(gcf,'Position'). You need to have opened a figure of standard size.

E.

E. (view profile)

Wonderful function!

However, had some problems using figures, generated with matlabfrag, as subfigures in LaTeX/pdfLaTeX. The resizing part messed up the label positions so that label ticks and labels itself overlapped. For me the trick was to resize the figures in MATLAB on beforehand. Here is howto:
First get screensize using:
get(0,'ScreenSize')
Size the latter two numbers corresponding to your scale and plot the required figures using:
figure('Position',[x y scaled1 scaled2])
where x and y equal the first two results of the screensize and the scaled1 and 2 represent the scaled values.
This did the trick for me.

Stefan Stefan

Hi there,

matlabfrag helped a lot to write good looking papers. Now I have a problem with intersecting axes labels and label ticks. I sent you an email with the necessary files to reproduce the problem. Looking forward to hear from you.
Regards,
Stefan

Hi, excellent tool!

I'd like to point out one thing (typo?) in the userguide.pdf, section 4.3. The userguide says you have to insert -shell-escape in order to make it work with pdflatex. But, I needed to insert --shell-escape, note the double -!

Cheers
Herwig

Martin

Martin (view profile)

Great work !!

I uploaded a small script to convert the tex and eps files into one pdf.

File ID is #28545.

Allan Leal

This is a great work!

I am wondering how could I get the EPS file already with the <<final>> format, I mean, with the tags already converted? I don't want to work with the TEX file.

Thanks.
A.

Allan Leal

Juan

Juan (view profile)

I manage to solve it. Apparently my windows version of pdftex does not support the font I was using in the rest of the document.

Juan

Juan (view profile)

I am trying with a Contour plot.(pdflatex + pstool) Everything looks perfect except for the contour numbers. They don’t appear in the pdf files (actually the number tags are there in the eps). Does it happened to somebody else ?.

Rory

Rory (view profile)

I am testing this because I get ridiculously big files with LaPrint, which according to Laurin's comment above should not happen with this package. However, the eps files that this produces are still far too large (~75mb vs 6mb when I do a simple print command).
Thanks in advance, if I can get this working it will be a real lifesaver for my thesis!

Zebb Prime

Zebb Prime (view profile)

Hi Michael,

The way I would do it is to just set all fonts to the size corresponding to \small. Of course this won't change if you wish to change to document fontsize.

You could open the output .tex file, and edit the \matlabtextA, etc commands to use \small instead of \fontsize.

The reason I chose to use \fontsize is that the label positioning is dependent upon the chosen fontsize. This way, if it looks ok on the screen, it should look ok in the document too.

Regards,
Zebb

Great package!

Suppose that I want to have all text in final figure typeset using \small, i.e., all figure text should be slightly smaller than the default tex-document's font. Any suggestions on how to do this?

Thanks!
Michael

Zebb Prime

Zebb Prime (view profile)

Hi Benjamin,

The version checking bug should already be fixed in the latest version.

Regards,
Zebb

Benjamin

So I decided to post a small solution.
Changes lines 48-53 from

v = version;
v = sscanf(v,'%i.%i');
v = eval( sprintf('%i.%i',v(1),v(2)) );
if v(1) < 7
error('matlabfrag:oldMatlab','Matlabfrag requires Matlab r2007a or newer to run');
end

to

v = version;
v = sscanf(v,'%i.%i');
if (v(1) < 7) || ((v(1) == 7) && (v(2) < 4))
error('matlabfrag:oldMatlab','Matlabfrag requires Matlab r2007a or newer to run');
end

Benjamin

It's a really great script. I used it to create the plots of my masters thesis. At the moment there is a small error with Matlab 7.10 . The script needs Matlab 7.3 or newer, but in the script 7.10 is recognized as 7.10<7.3 .

Zebb Prime

Zebb Prime (view profile)

Hi all,

Please disregard my use of \include in my comments above. Please use \input instead.

Cheers,
Zebb

Rob Campbell

Rob Campbell (view profile)

Zebb Prime

Zebb Prime (view profile)

Hi All,

Viton: That should be possible, but I don't have time to do implement anything like that at the moment.

Andrey: That should only be necessary if you aren't grouping the figures properly. They placing \begin{psfrag} \end{psfrag} around your \include and \includegraphics.

Vincent: There isn't a way to do this using the default axis labels in matlab. You could however convert the axis labels to text objects. There are several functions that do this in the FEX, one is http://www.mathworks.com/matlabcentral/fileexchange/23841-format-tick-labels-extended (disclaimer - I haven't used this file myself)

David: What version are you using? You haven't provided enough information for me to diagnose the problem. Make sure you are using the latest version, and email me an example of the problem.

Hans: I did a quick test, and it looked the same in the document as it did on the screen. The easiest way to fix this would be to manipulate the position handles of legend, and if necessary the axis.

I also want to remind everyone that the comment section isn't a very good medium for receiving support.

Cheers,
Zebb

Hi,
Thanks, it is very great.
I have a problems with the location of my legend. It always seem to overlap with the xlabel when I use SouthOutside. Is there a way to avoid this?
Thanks in advance
Hans

David

David (view profile)

I have a lot of success with matlabfrag, but I find that the print command still resizes the legend box, it is very frustrating.

If I force the rendereer to be opengl or zbuffer the legend box is in the right place but the box lines on the legend and the figure are blurry.

Please please can somebody help me with a solution for this problem?

Hi Andrey,

one way to solve your problem is by rescaling the eps plots to smaller sizes.
try
\includegraphics[scale = 'value < 1']{filename}

This happens when I rescale the plots to be used in a sub plot

Thanks alot! However in my tex plots axis labels seem to get closer to axes than they are in the actual matlab pics. Is there any way to space axis labels further away from axes?

Is it possible to make matlabfrag output unique psfrag command numbers for every eps file? I'm including two eps files in one figure using the subfigure command, and the labels get all mixed up because some of the psfrag command numbers are the same for both files. I've tried to move the \input{*.tex} commands right before the relevant \subfigure and it worked but it had some undesirable side effect, ie the figures got stacked vertically instead of being side by side. So basically I want to include the *.tex files for both figures beforehand without messing the labels. I can change the numbers in the eps and tex files by hand of course but it's too ineffective.

Viton Vitanis

Excellent piece of code! I'm wondering whether there is some automatic way to modify the size of the legend box during latex compilation so that it adapts to any font being used there.

Very nice work!

Laurin

Laurin (view profile)

I've been looking for exactly this program for about a year now. :)

Until now I used LaPrint for almost all of my Matlab -> Latex printing jobs. For me the biggest drawback of LaPrint is that it can only handle the Matlab "painters" renderer. In my diploma thesis I have many pcolor and isosurface plots (with nice phong lighing). With the "painters" renderer the first resulted in huge file sizes even when "downsampling" my data matrices to reasonable sizes while the latter where completely impossible to realize. With matlabfrag now even transparency works!

With matlabfrag I can now also put all my graphics in a subdirectory without manually modifying all of the tex-files like in LaPrint!

Keep up the good work!

Tor

Tor (view profile)

Extraordinary work! A lot better than LaPrint, I rarely need to fight this script. However, I do occasionally get a legend box that's too small for the legend text (the right hand side of the box cuts of a few letters). Usually solved by adding a "\," or two.

Zebb Prime

Zebb Prime (view profile)

Hi Matt,

I generally leave the font as the default (Helvetica). That said, matlabfrag should work with any font you choose in Matlab.

Cheers,
Zebb

Matt

Matt (view profile)

Hi, I'm finding this code (and pstool) to be very useful.

I would, however, like to know what font you use in matlab in order to get your legend sizing to work out in pdflatex.

Excellent! Found it much more useable than laprint, and now can cope with transparency (use the opengl renderer).

Kamil Wojcicki

Kamil Wojcicki (view profile)

Great job, thanks!

Zebb Prime

Zebb Prime (view profile)

Hi Rui,

The idea is that ['number'] gets written out to the eps file, and the tex file contains instructions (using the psfrag LaTeX package) to substitute it for the original label.

In LaTeX you can do this in two ways:
1. Load the psfrag package, and then when including the graphics, include the tex file:
\include{figure.tex}
\includegraphics{figure.eps}
-- This way only works with latex.

2. Load the psfrag and pstool packages, and use the command
\psfragfig{figure}
instead of the includegraphics command. This works for both latex (from pstool v1.2 on) and pdflatex.

Please contact me via email if you need more information.

Cheers,
Zebb

Rui

Rui (view profile)

hi.. great program. congratulations
but how can i avoid the axis text having this format: " [ 'number' ] "

Updates

1.26

Fixed a bug that occurred when a figure wasn't frontmost.

1.25

Documentation update: for plain LaTeX, \input should be used instead of \include.

1.24

Fixed a version checking bug which caused it to break in r2010a, and a EPS integer overflow bug.

1.23

Fixed a bug to do with blank strings, and a bug to do with baseline alignment.

1.22

Changed default painters dpi to 3200, and fixed my broken usage of inputParser.

1.21

Fixed a bug that occurred with [xyz]ticks set outside [xyz]lims.

1.20

- Added a test for empty ticks, while ticklabels are not empty.
- Added sections for Legends and the 'Unable to interpret TeX string' warning in the userguide.

1.19

- Removed AutoTick test from axis scalings, and updated the user guide to reflect this.

1.18

- Text alignment tweaks (hopefully for the better). In particular, x-tick labels should be vertically aligned better.
- Bug fixes: z-tick label alignment and no-text detection.

1.17

Fixed a bug that occurred if some (but not all) the tick labels are empty.

1.16

Fixed the horribly broken compatibility for r2007a and r2007b.

1.15

Improved alignment of negative xtick labels.
Legend callback should be suppressed during printing.

1.14

Improved tick label positioning.

1.13

Fixed some of the annoying resizing issues again.

1.12

Fixed support for rotated text when using the zbuffer and opengl renderers.

1.11

- Preliminary support for the opengl and zbuffer renderers.

1.10

- Fixed a bug that occurred when the figure being exported had no text in it.

1.9

- Better handling of axis tick labels and changed the substitution text format.
- More examples.
- Improved User Guide.

MATLAB Release
MATLAB 7.8 (R2009a)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video