Legend in a loop for two graphs

조회 수: 3 (최근 30일)
ikram ros salamat
ikram ros salamat 2021년 3월 5일
댓글: ikram ros salamat 2021년 3월 5일
Hello,
So I have a code for two plots but one of the plot changes with each loop. I want to be able to write down the legend which shows the value that makes the plot change. So far I have this code, however when I run it, my second legend that should show the word 'Signal' get over written by num2str(i).
Thanks.
V = 1;
x = [0:0.01:15];
y = V*sin(x/2); % studied function
a0= (4/pi)*V;
n = 3;
sum = 0;
for i=1:n
an = 4/(1-4*i^2)*(V/pi);
sum = sum + an*cos(i*x);
f = a0/2 + sum;
figure();
%% plot 1
plot(x,f,'LineWidth',1.5);
hold on
%% plot 2
plot(x,abs(V*sin(x/2)),'LineWidth',1.5);
legend('Expansion for n =',num2str(i),'Signal','location', 'best');
grid minor;
ylim([0 1.5]);
hold on
end

채택된 답변

nines
nines 2021년 3월 5일
Hello!
Is this what you are trying to do:
if so, here is the code (all I did was some rearranging):
V = 1;
x = [0:0.01:15];
y = V*sin(x/2); % studied function
a0= (4/pi)*V;
n = 3;
sum = 0;
for i=1:n
an = 4/(1-4*i^2)*(V/pi);
sum = sum + an*cos(i*x);
f = a0/2 + sum;
figure();
%% plot 1
plot(x,f,'LineWidth',1.5);
hold on
%% plot 2
plot(x,abs(V*sin(x/2)),'LineWidth',1.5); hold on
legend(['Expansion for n =' num2str(i)],'Signal','location', 'best');
grid minor;
ylim([0 1.5]);
hold on
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by