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

5 visualizaciones (últimos 30 días)
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:

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 19 de Mayo de 2020
Editada: Ameer Hamza el 19 de Mayo de 2020
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');

Más respuestas (0)

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by