How to create multiple legends - depending on number of inputs

So I basically have this function y which varies on a chosen number nabla. I have written a function that takes in a chosen number of nablas and plots the corresponding y value to a given x interval, here it is:
if true
function nablaplot(n)
%writing in the number n of inputs and creating a matrix
%calculating my matrix y which I will plot
for i=1:n
nabla(i)=input(sprintf('Enter nabla value number %i: ',i));
y(i,:) = 2.*x - 2.*x.^3 + x.^4 + (nabla(i)/6).*x.*(1-x).^3 ;
end
x=0:0.01:1; %step length
figure
y1= 0*x; %x-axis
plot(x,y1,':black') %x-axis
hold on
plot(x,y) %here I plot the number n of graphs
axis([0 1 -0.2 2]) %boundaries
hold off
end
end
This function prints the given number n of graphs into a single plot - which is what I want! But is there any way to plot n legends which states what nabla value each graph has?

3 commentaires

But this function opens a new figure for every iteration. Do you want a legend in every figure?
Jakob
Jakob le 26 Oct 2017
Modifié(e) : Jakob le 26 Oct 2017
I think you have to open the figure first and hold it. Then use 'legend('nabla1', 'nabla2',...)' to draw the legend, the nablas have to be in the right order, tho. So first open figure and hold it before you begin the loop. everything should be plotted in that figure then.
I dont know if you can use 'legend(['nabla' i])' at each iteration, if it doesnt work, just use legend after you finished the loop, with an array containing all the names for the nablas.
Is there an efficient way to add different colors to each nabla in this same 'for' loop?

Connectez-vous pour commenter.

 Réponse acceptée

Jakob
Jakob le 26 Oct 2017
Modifié(e) : Jakob le 26 Oct 2017
for example:
figure;
hold on;
x=1:10
for i=1:3
plot(i*sin(x));
nabla(i)=i;
end
leg=string(nabla); %converts integer-array to string array
legend(leg);
So your values for nabla have to be in a string array and in the right order, which is the input to the legend(...) function.

1 commentaire

Hi, I used this and worked out a solution, thanks! (Changed nabla to lambda)
figure
hold on
plot(x,y) %here I plot the number n of graphs
axis([0 1 -0.2 2]) %boundaries
grid on
leg = string(lamdba);
for j = 1:n
leg(j) = '\Lambda = ' + leg(j);
end
legend(leg)

Connectez-vous pour commenter.

Plus de réponses (0)

Produits

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by