How to include function in legend

28 ビュー (過去 30 日間)
Niklas Kurz
Niklas Kurz 2021 年 6 月 3 日
コメント済み: Star Strider 2021 年 6 月 3 日
I tried all possibl string2functions of Matlab, but not getting quiete the result.
Here's my best try:
syms x
F = x^2; % Definied Function
g = matlabFunction(F);
% some random steps
x = -10:0.1:10;
f = g(x);
p1 = plot(x,f);
hold on
n = 20;
C = jet(n);
for k= 1:n
p2 = plot(x,f+2*k,'Color',C(k,:));
end
% Here comes the questionable part.
legend([p1,p2],{strcat('f = ',char(F)),sprintf('f at n = %0.f',n)},...
'Interpreter','latex','FontSize',20)
Basically I want the function that I definied to be automatically updated in legend. (Pretty handy if you change f multiple times). However in my attemp I get a warning:
String scalar or character vector must have valid interpreter syntax:
f:x^2
How can the function be acknowledged by the interpreter?

採用された回答

Star Strider
Star Strider 2021 年 6 月 3 日
A sllightly different approach —
syms x
F = x^2; % Definied Function
g = matlabFunction(F);
% some random steps
x = -10:0.1:10;
f = g(x);
p1 = plot(x,f);
hold on
n = 20;
C = jet(n);
for k= 1:n
p2 = plot(x,f+2*k,'Color',C(k,:));
end
% Here comes the questionable part.
legend([p1,p2],{sprintf('$f = %s$',char(F)),sprintf('$f\\ at\\ n = %0.f$',n)},...
'Interpreter','latex','FontSize',20)
.
  2 件のコメント
Niklas Kurz
Niklas Kurz 2021 年 6 月 3 日
I reckognized 'latex(F)' instead of 'char(F)' is just more accurate at displaying functions like But either way it is working now! Just the right tweeking.
Star Strider
Star Strider 2021 年 6 月 3 日
Great!
Thank you!

サインインしてコメントする。

その他の回答 (1 件)

Joseph Cheng
Joseph Cheng 2021 年 6 月 3 日
編集済み: Joseph Cheng 2021 年 6 月 3 日
do you need to use latex as just using the default tex? as latex uses $ for markup of symbols i don't know if it'll take the syms function very well without some edits. if you get rid of the interpreter setting and use the default one
syms x
F = x^2; % Definied Function
g = matlabFunction(F);
% some random steps
x = -10:0.1:10;
f = g(x);
p1 = plot(x,f);
hold on
n = 20;
C = jet(n);
for k= 1:n
p2 = plot(x,f+2*k,'Color',C(k,:));
end
% Here comes the questionable part.
legend([p1,p2],{strcat('f = ',char(F)),sprintf('f at n = %0.f',n)},...
'FontSize',20)
more info can be found here in another matlab tex vs latex answers sub
  1 件のコメント
Niklas Kurz
Niklas Kurz 2021 年 6 月 3 日
編集済み: Niklas Kurz 2021 年 6 月 3 日
Well, latex just looks more beautiful in my eyes :$

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeConversion Between Symbolic and Numeric についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by