How to use num2str inside text with latex interpreter?

Hi to everyone, I want to assign a number to a string inside a text command to dynamically change the output of the text inside the plot.
Here is an attempt of coding:
clc;clear all;close all;
figure
i=1
i = 1
plot(1:6,2:7)
text(2,4,'$L_{1}$','Interpreter',"latex");
text(4,5,'$L_{',num2str(i),'}$','Interpreter',"latex");
Error using text
Unrecognized property 1 for class Text.
Can you help me to correclty code the last line?

 채택된 답변

I prefer to use sprintf for this. (If you use any escape characters, you need to use double backslants. See the documentation for detais.).
figure
i=1
i = 1
plot(1:6,2:7)
text(2,4,sprintf('$L_{%d}$',i),'Interpreter',"latex");
text(4,3,sprintf('$L_{\\frac{%d}{2}}$',i),'Interpreter',"latex");
.

댓글 수: 4

Thank you. Can you explain the differences, if they exist, with "num2str"?
My pleasure!
I suspect sprintf uses num2str (or something like it) ‘under the hood’. The difference is that sprintf (and its friends) are intended to mix text, various numeric, character, and string variables easily in the same function call, and define their display formats with appropriate formatting.
The sprintf function (and its friends) just make everything easier, the reason I use them.
Clear explaination! Thanks aganin!
As always, my pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Jeff Miller
Jeff Miller 2022년 10월 7일
I think you need square brackets like this to assemble all the characters into a single string
text(4,5,['$L_{',num2str(i),'}$'],'Interpreter',"latex");
dpb
dpb 2022년 10월 7일
i=1;
text(0.4,0.5,"L_{" + i + "}")
i=i+1;
text(0.4,0.4,"\it L_{" + i + "}")
i=i+1;
text(0.4,0.3,"\it L\rm_{" + i + "}")
Variations on a theme; the above doesn't require LaTeX; the default TeX interpreter can manage on its own.

카테고리

도움말 센터File Exchange에서 Annotations에 대해 자세히 알아보기

제품

릴리스

R2022a

질문:

2022년 10월 6일

댓글:

2022년 10월 7일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by