MATLAB: How to setup legend for a figure with two axes (left and right)

figurelegendlinemultiple axesplotplotyyright axesright axis

I have a figure with two axes (left and right). 2 lines on left axis and one line on right axis. I can not get all legends in one box using following code.
PS. I have read previous discussions (links below) on this topic but does not seem to work for me!
x = 0:0.01:10;
y11 = sin(x);
y12 = cos(x);
y2 = ones(1001,1);
figure;
ax(1) = axes('position',[0.1 0.1 0.8 0.8]);
ax(2) = axes('position',[0.1 0.1 0.8 0.8], 'yaxislocation','right','color','none');
line('parent',ax(1),'xdata',x,'ydata',y11,'color','b');
line('parent',ax(1),'xdata',x,'ydata',y12,'color','g');
line('parent',ax(2),'xdata',x,'ydata',y2,'color','r');
legend( [ax(1) ; ax(2)] , {'sin','cos','one'} )

Best Answer

You can create the legend using the handles of your line objects:
l1=line('parent',ax(1),'xdata',x,'ydata',y11,'color','b');
l2=line('parent',ax(1),'xdata',x,'ydata',y12,'color','g');
l3=line('parent',ax(2),'xdata',x,'ydata',y2,'color','r');
legend( [l1;l2;l3] , {'sin','cos','one'} );