Add subsequent plot to legend in matlab -


i doing iterative process create figure, add plot , append legend item. doing series of commands have collected in script below. please note cannot script since actual plotting depends on external processes must physically iterate since have no control on them.

>> x = [0:1:10] >> y1 = [] >> y2 = [] >> y3 = [] >> figure >> hold on  >> = 1:size(x,2)     y1(i) = x(i)^2 end  >> plot(x,y1,'b') >> legend('x^2')  >> = 1:size(x,2)     y2(i) = 2*x(i)^2 end  >> plot(x,y2,'r') >> legend('2*x^2')  >> = 1:size(x,2)     y3(i) = 3*x(i)^2 end  >> plot(x,y3,'g') >> legend('3*x^2') 

as expected creates plot 3 functions of interest legend containing last item. not happy since when series of commands must each time create new legend old items new ones. achieve desired result commands must modified follows

>> x = [0:1:10] >> y1 = [] >> y2 = [] >> y3 = [] >> figure >> hold on  >> = 1:size(x,2)     y1(i) = x(i)^2 end  >> plot(x,y1,'b') >> legend('x^2')  >> = 1:size(x,2)     y2(i) = 2*x(i)^2 end  >> plot(x,y2,'r') legend('x^2','2*x^2')  >> = 1:size(x,2)     y3(i) = 3*x(i)^2 end  >> plot(x,y3,'g') >> legend('x^2', 2*x^2','3*x^2') 

what efficient way append added plot current legend without having rewrite previous content? thanks.

you cannot append legend, can recall without having know came before. relies on assigning legend variable, , using string property recall previous entries.

% define plotting variables here x=0:0.1:1; y1=x.^2; y2=2*x.^2; y3=3*x.^2; % initialise figure    figure; hold on; % plot 1 plot(x, y1, 'b'); l = legend('x^2'); % plot 2 plot(x, y2, 'r'); l = legend([l.string, {'2*x^2'}]); % plot 3 plot(x, y3, 'k'); l = legend([l.string, {'3*x^2'}]); 

result:

plot


Comments

Popular posts from this blog

cookies - Yii2 Advanced - Share session between frontend and mainsite (duplicate of frontend for www) -

angular - password and confirm password field validation angular2 reactive forms -

php - Permission denied. Laravel linux server -