Having difficulties in generating correct legend in subplot

1 view (last 30 days)
I'm trying to generate the appropriate legend for the following plot:
clear all;
n=[300 600];
for m=1:length(n)
t_0=0;
t_n=3;
h=(t_n-t_0)/n(m);
t=t_0:h:t_n-h;
y_e1=zeros(size(t));
for i = 1:n(m)
y_e1(i)= cos(t(i));
end
y_e=zeros(size(t));
for i = 1:n(m)
y_e(i)= sin(t(i));
end
diff=max(abs(y_e-y_e1));
ratio_ratio=diff(1)/diff(2);
subplot(2,1,m)
hPlotf(m)=plot(t,y_e1,'*');hold on;
hPlotf1(m)=plot(t,y_e,'o');%hold off
end
% legend('n=300','n=300','n=600','n=600')
a=axes('position',get(gca,'position'),'visible','off'); % a is the current axis handle
hLf = legend(a,hPlotf,'t=300','t = 600','Location','best'); %hLf - legend handle for f
hLf1 = legend(hPlotf1,'t=300','t = 600','Location','best'); %hLf1 - legend handle for f1
However, I'm not getting the correct one. Moreover, I would like to evaluate the ratio of two absolute maximum. Your help will be appreciated.

Answers (1)

KSSV
KSSV on 16 Mar 2022
Edited: KSSV on 17 Mar 2022
You need not to use loop. I have edited the code, check it.
n=[300 600];
for m=1:length(n)
t_0=0;
t_n=3;
h=(t_n-t_0)/n(m);
t=t_0:h:t_n-h;
y_e1=cos(t);
y_e=sin(t) ;
subplot(2,1,m)
plot(t,y_e1,'r','DisplayName',['n =',num2str(n(m))]);hold on;
plot(t,y_e,'b','DisplayName',['n =',num2str(n(m))]);
legend show
end
  2 Comments
Moslem Uddin
Moslem Uddin on 16 Mar 2022
Thanks. We're expected to get , not . For this we need to fix as follow. Any idea for the ratio? I mean the last part of the question
['n =',num2str(n(m))]

Sign in to comment.

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!