How to create multiple legends - depending on number of inputs

4 views (last 30 days)
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 Comments
Jakob
Jakob on 26 Oct 2017
Edited: Jakob on 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.
Erica Miller
Erica Miller on 4 Jun 2021
Is there an efficient way to add different colors to each nabla in this same 'for' loop?

Sign in to comment.

Accepted Answer

Jakob
Jakob on 26 Oct 2017
Edited: Jakob on 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 Comment
Jonas Ravndal Kildal
Jonas Ravndal Kildal on 26 Oct 2017
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)

Sign in to comment.

More Answers (0)

Tags

Products

Community Treasure Hunt

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

Start Hunting!