Ash
Ash

Reputation: 328

Matlab - latex format spacing

I am creating a legend like so,

theta = [90 120 80 120];
phi   = [120 120 180 180];


for i=1:length(theta)
    plot_legend{i} = sprintf('\\theta=%3d\\circ\\phi=%3d\\circ',theta(i),phi(i))
end

This gives me my desired output

plot_legend = 
'\theta= 90\circ\phi=120\circ'
'\theta=120\circ\phi=120\circ'
'\theta= 80\circ\phi=180\circ'
'\theta=120\circ\phi=180\circ'

But when this is interpreted by the TeX interpreter, the leading space is neglected, which I find a tad annoying. Is there a simple TeX way to ensure that the spacing is maintained?

But the spacing is not maintained when called through legend.

legend(plot_legend,'interpreter','latex')

Upvotes: 2

Views: 5605

Answers (1)

LowPolyCorgi
LowPolyCorgi

Reputation: 5171

Here is a general solution to replace the first padding zeros with LaTeX-interpreted spaces:

% --- Definition
theta = [5 120 80 120];
phi   = [120 120 180 180];

% --- The function handle that does the job
f = @(x, n) regexprep(num2str(x, ['%0' num2str(n) 'i']), '^(0+)', '${repmat(''\\hspace{0.5em}'', [1 numel($0)])}');

% --- Create a plot and the legend

hold on
for i = 1:length(theta)

    % Fake curve
    ezplot(['x^' num2str(i)]);

    plot_legend{i} = ['$\theta=' f(theta(i),3) '^\circ,\ \phi=' f(phi(i),3) '^\circ$'];
end

legend(plot_legend, 'interpreter', 'latex')

And the result:

enter image description here

You can specify the length of the number with the second parameter of the function handle. Note that this only works with integer values.

Best,

Upvotes: 2

Related Questions