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

조회 수: 8 (최근 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 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