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

8 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Legend 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by