Legend in a loop for two graphs

3 次查看(过去 30 天)
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