How do I add a legend in a for loop of variables from an array?

5 ビュー (過去 30 日間)
Carly Hudson
Carly Hudson 2020 年 5 月 19 日
編集済み: Ameer Hamza 2020 年 5 月 19 日
Hello, I am attempting to input of an array into a legend, in a for loop. I am having trouble, but I think I am almost there.
A = [1,3,5,7,9];
anonF = @(x) A*sin(x) + (2.*(x.^2));
for k = 1:length(A)
fplot(anonF, [0,05]);
hold on
legendInfo{k} = ['A = ' A(k)]; %legendInfo{i-1} = ['X = ' num2str(i-1)];
hold on
legend(legendInfo,'Location','northwest');
end
%Defining Graph (not legend)
title('Simple Function Plot');
xlabel('x-values');
ylabel('y-values');
I need the values in the legend to say "A = 1 A = 3 A = 5 ..." but this is how it is graphing right now:

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 5 月 19 日
編集済み: Ameer Hamza 2020 年 5 月 19 日
First, you need to use num2str() to convert a numeric value into a char array, which can be displayed in the legend. Otherwise, it will likely display the Unicode equivalent of that numeric value. Also, I have made some modifications to make the function more compact. There was also the issue with the definition of function handle anonF. I have corrected that too
A = [1,3,5,7,9];
anonF = @(a,x) a*sin(x) + (2.*(x.^2));
hold on
for k = 1:length(A)
legendInfo = ['A = ' num2str(A(k))];
fplot(@(x) anonF(A(k), x), [0,05], 'DisplayName', legendInfo);
end
legend('Location', 'northwest');
%Defining Graph (not legend)
title('Simple Function Plot');
xlabel('x-values');
ylabel('y-values');

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLegend についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by