How do I add a legend in a for loop of variables from an array?
조회 수: 9 (최근 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:
댓글 수: 0
채택된 답변
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Legend에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!