Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MatLab latex title doesn't work for powers (^)

Tags:

latex

matlab

In MatLab (R2015a), I want to style the title of my plots using latex.

This is working fine for some functions, but not if there's a power in the equation.

The below code works, and shows a formatted title to the right, and an unformatted title to the left.

It shows the warning:

Warning: Error updating Text.

String must have valid interpreter syntax: y = x^2

syms x y
eq = y == x^2;
subplot(1,2,1)
ezplot(eq)
title(latex(eq),'interpreter','latex')

eq = y == x+2;
subplot(1,2,2)
ezplot(eq)
title(latex(eq),'interpreter','latex')

EDIT:

I just found out I can get it to work by appending $ on both sides. But it seems weird that I would have to do this.

So this works:

title(strcat('$',latex(eq),'$'),'interpreter','latex')
like image 918
wvdz Avatar asked Dec 30 '25 22:12

wvdz


1 Answers

Solution

The problem can be solved easily by adding $-signs before and after the generated LaTeX-expression. So you can change your «title-lines» to:

title(['$',latex(eq),'$'],'interpreter','latex')

An alternative is to use strcat as proposed in your question.


Explanation

Since you basically answered the question yourself already, I'm going to explain why it happened. Hopefully after reading this, it's no longer 'weird' behaviour. If you choose to use the LaTeX-interpreter in Matlab, you really get a LaTeX-interpreter. This means that the provided string must be valid LaTeX-syntax.

Using ^ outside a math-environment is considered invalid syntax because it is a reserved character in LaTeX. Some interpreters automatically add the $ before and after in this case, but throw a warning at the same time.

The output of the latex-function in Matlab is provided without the $-signs. This way you can combine outputs and concatenate if needed without creating a mess with $-signs.

To change to the math-environment in LaTeX you can use the already mentioned shortcut $...$. An alternative way is to use \begin{math} your_equation \end{math}. It produces the same result for your equations and can be used here for demonstration purposes. The following line would do the same job, but is a bit longer to write:

title(['\begin{math}',latex(eq),'\end{math}'],'interpreter','latex')

Now, the reason why only one of your equations is displayed correctly, lies in the invalid character ^ in y = x^2. Matlab then chooses interpreter none and therefore displays the string unformatted. The +-sign in y = x + 2 is valid outside a math-environment, so it gets displayed correctly (but is not interpreted in a math-environment).

like image 95
Matt Avatar answered Jan 01 '26 12:01

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!