Legend in a loop for two graphs

3 views (last 30 days)
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

Accepted Answer

nines
nines on 5 Mar 2021
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

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!