LaTeX in MATLAB multi-line titles - matlab

I need to create a two-line title in a MATLAB plot, using LaTeX in each of the lines.
title({'first line','second line'})
works, but not with LaTeX. In a single line MATLAB title, LaTeX is understood as in the example:
title(['$y=x^2$'],'interpreter','latex')
I have tried many things, but I haven't managed to have MATLAB produced a multi-line title with LaTeX in those lines.

If you run
title({'$y=x^2$','$y=x^2$'},'interpreter','latex')
you will get a two-line title with correct LaTeX-ification.

Up to version R2017a, using a cell array, as suggested by other answers,
forced left alignment. This seems to have been fixed in R2017b.
You can wrap the title in a LaTeX tabular environment:
figure;
plot((1:5).^2);
title('\begin{tabular}{c} first_line \\ second_line \end{tabular}', ...
'interpreter', 'latex')
This will let you choose text alignment. Replace {c} with either {r} or {l}, for right and left aligned text, respectively.

You can use sprintf to create the string for the title, explicitly with a newline character, '\n'.
title(sprintf('$y=x^3$\n$sin(x)$'), 'interpreter', 'latex');

Related

Saving figure to pdf prints # instead of tabs in titles

if I create a plot with some tabs in the titles and try saving that to a local pdf file (via print function), I get some hashtags instead of tabs in the pdf. This does not occur in the visible figure.
For example, I plotted the residuals of an approximant to the runge function on a grid:
plot(g, f(g) - runge(g));
title(sprintf('residuals,\t max_x(s-f) = %.3f', max(f(g)-runge(g))));
Then after some axes manipulation (grid, boxes, etc..) I execute
h = gcf;
set(h,'Units','Inches');
pos = get(h,'Position');
set(h,'PaperPositionMode','Auto','PaperUnits','Inches','PaperSize',[pos(3), pos(4)])
print(h,'data/runge_example.pdf','-dpdf','-r200')
close(h)
Is somebody aware of that behaviour or better able to found that as already solved than I am?
EDIT: Same behaviour with saveas and saving to eps. This does not happen with \n
EDIT2: I'm using Matlab Version R2017b (9.3.0.7...)
So, after a long discussion we figured out that we have no idea of how to use tabs in matlab titles in combination with latex mode.
To clarify: use math environments and escape tex directives, otherwise it will throw an error.
so
sprintf('residuals,\t $max_x(\\vert s-f\\vert) = %.3f$', max(f(g)-runge(g))));
will give you a nice string:
residuals, $max_x(\vert s-f\vert) = 0.264$
The problem is, that it really is a tab. And the matlab latex interpreter (don't know which one that uses, the system or an own) crashes on that. I copy-pasted that to a tex document and pdflatex ran fine on it (but not showing that much space unfortunately).
So, I came up with the following fix:
use the latex directive \quad or \qquad:
title(sprintf('residuals,\\quad $max_x(\\vert s-f\\vert) = %.3f$', max(abs(f(g)-runge(g)))));
This will give you more space than a normal space.
EDIT: For this to work you need the interpreter of matlab to be set to "latex" instead of the default "tex". Do this by changing the title to
title(title_string, 'Interpreter', 'latex')
or by setting (globally for that script)
set(groot, 'defaultTextInterpreter', 'latex')

Justify legend text in Matlab

I have the legend shown below:
On the left, the text is aligned, however, on the right the numbers are not aligned. How can I align the numbers too?
The tab command (\t) does not seem to work when providing strings to table entries. However, you can solve the problem if you work in the latex environment, define every entry as a single-row tabular and define the first column to have a specific width (e.g. 1 cm):
plot(eye(2)); % example plot
h=legend('\begin{tabular}{p{1cm}r}first:&1\end{tabular}',...
'\begin{tabular}{p{1cm}r}second:&2\end{tabular}'); % table entries in latex
set(h,'interpreter','latex'); % set interpreter

Matlab: How to avoid italic font for plot labels when interpreter is latex?

let's say that one plots something and either for title or legend or labels uses interpreter as latex, by default the title or ... will be shown in italic, how can one suppress that?
for instance for y-axis label it is as below:
ylabel('$\frac{P_{shape}}{P_{circle}}$','FontSize', 28,'Interpreter','LaTex')
Your question is actually related to Latex and not related to MATLAB!
\mathrm is used for that purpose in Latex.
Anyway, the following will achieve your desired result:
ylabel('$\mathrm{\frac{P_{shape}}{P_{circle}}}$','FontSize', 28,'Interpreter','LaTex')

Issue Matlab EPS figures

I have a problem when I create a EPS figure which I want to include in Latex. Somehow I am unable to place a caption above the figure created with Matlab. It gets overwritten by whitespace. I have created a minimum working example. The figure in matlab is created according the following code:
plot(1:10)
title('A line')
print('test','-depsc2')
And the corresponding latex file:
\documentclass[a4paper]{article}
\usepackage{graphicx}
\begin{document}
\begin{figure}[h]
\caption{Caption is overwritten}
\includegraphics[width=\textwidth]{test.eps}
\end{figure}
\end{document}
No caption is visible in the output pdf. I am a dvi-ps-pdf chain.
It seems to be an issue with the bounding box values. If I add go to the draft mode of graphicx (\usepackage[draft]{graphicx} ) the caption appears.
Thanks for any help.
Best, Rob
Try the clip option in includegraphics:
\includegraphics[width=\textwidth, clip]{test.eps}
You may also want to include some vertical space between caption and figure:
\caption{Caption is overwritten}
\vspace{5mm}
\includegraphics[width=\textwidth, clip]{test.eps}

MATLAB: latex interpreter font spacing

The font spacing in TeX-typeset equations in MATLAB defaults to being highly compressed. Is there a way to increase the amount of spacing, so that, for example, the numerator and denominator of a fraction do not make contact with the line separating the two?
plot(1:10,rand(1,10));
set(gca,'FontSize',18);
legend('$\frac{xy}{\exp\left(\frac{x}{y}\right)}$');
set(legend(),'interpreter','latex');
I think the easiest way is to use some LaTeX trickery.
Long story short, in LaTeX $ ... $ is used for inline math, but for display math, you should either use \[ ... \] or the legacy way of doing the same $$ ... $$. For LaTeX documents, don't use the latter, but for MATLAB it should be enough.
The difference between inline math and display math, is like the difference between using backticks (``) and indentation in StackOverflow. The first will show your code in-between text, the latter in-between paragraphs. With math, only display mode math will have decent lay-out for larger formulas.
So the following code should fix your problem:
plot(1:10,rand(1,10));
set(gca,'FontSize',18);
legend('$$\frac{xy}{\exp\left(\frac{x}{y}\right)}$$');
set(legend(),'interpreter','latex');
If you want even more, you might want to consult the Not So Short Introduction To LaTeX2e which gets you started with a lot of the tricks of the LaTeX trade.
edit:
What I tend to use as a trick to improve spacing in formulae is using phantoms (\phantom, \vphantom, \hphantom), but \vspace or \vskip might be a little cleaner to use.
Looking through the list of properties for the legend, there doesn't seem to be any way of specifying a line spacing that is consistent with automatic positioning. You can fudge the line spacing by enlarging the box, however, by changing the final entry (height) in the OuterPosition property. It seems the placement of the box is based on its bottom-left corner, so if your legend box is in a North position then you will also need to reduce the second entry (y-position) by an equal amount.
In this example I increase the height of a North-positioned legend box by 25% (which I have found that gives nice results), which increases the line spacing.
h = legend(s1,s2,s3, 'location', 'northeast');
set(h, 'fontsize', 16, 'interpreter', 'latex')
outerposition = get(h, 'OuterPosition');
delta_h = 0.25*outerposition(4);
outerposition(2) = outerposition(2) - delta_h;
outerposition(4) = outerposition(4) + delta_h;
set(h, 'OuterPosition', outerposition)
You have to be wary about resizing the figure after running this code fragment, since changing the OuterPosition property clears the automatic placement of the box with respect to the plot axes. If you resize the figure the legend box will go walkabouts.