MATLAB: Plotyy legend for multiple lines ( R2012a)

legendplotyy

Hello ,
I am trying to plot a legend for multiple graphs in the plotyy mode. I have seen solutions like this:
legend([H1;H2],'Susceptibles','Infected','Concentration');
But how can i do it for every single line h(3)-h(9) ?
Thanks a lot
% Bed profile and velocities
subplot(2,1,1)
[ax,h1,h2]=plotyy(x6,y6,x1,y1)
h(3) = line(x7,y7, 'Parent', ax(1));
h(4) = line(x8,y8, 'Parent', ax(1));
h(5) = line(x9,y9, 'Parent', ax(1));
h(6) = line(x18,y18, 'Parent', ax(2));
h(7) = line(x19,y19, 'Parent', ax(2));
h(8) = line(x20,y20, 'Parent', ax(2));
h(9) = line(x21,y21, 'Parent', ax(2));
set(ax(1),'ytick',linspace(min(y6),max(y6),8));
set(ax(2),'ytick',linspace(min(y1),max(y1),3));
ylim(ax(1),([0 2.5]))
ylim(ax(2),([0 0.35]))
ylabel(ax(1),'u [m/s]')
xlabel('x [m]');
ylabel(ax(2),'y [m]')

Best Answer

I no longer have access to R2012a, so I tested this in R2017a.
See if something like this works:
x = linspace(0, 2*pi,500); % Create Data

y = sin([1:6]'*x); % Create Data
figure(1)
[ax,h(1),h(2)]=plotyy(x,y(6,:),x,y(1,:)*2);
h(3) = line(x, y(3,:), 'Parent',ax(1));
h(4) = line(x, y(4,:)*1.5, 'Parent',ax(2));
legend(h, 'Line 6', 'Line 1', 'Line 3', 'Line 4')
Since you are storing the line handles in an array, just use the array itself as the argument to legend.