Plot all for loop results

1 view (last 30 days)
I'm doing this exercise about ploting sine waves. The program uses two sine waves. The first one has the same frequency always (f1). The second one changes value (f2= [9 9.5 13 15]). The exercise is almost done, I just need to plot all figures for each of the four for loop iterations. When I run the program I can see the plots but they are quickly replaced by the next iterations. At the end I end up with three figures and I need all twelve. How can I keep all twelve?
%% Second Wave HW.
clc
t=linspace(1,20,10000); %10000 Datapoints
f1=8;
f2=9;
A=1;
for f2=[9 9.5 13 15]
w= A*sin(f1*t); %Blue Wave
w2=A*sin(f2*t); %Red Wave
% First Graph:
figure(1)
plot(t(1:1000),w(1:1000)) %Only Graphing 2T
hold on
plot(t(1:1000),w2(1:1000))
hold off
title(['Frequencies used= ',num2str(f1),' and ',num2str(f2)])
ylabel(['Amplitude= ',num2str(A)])
% Second Graph:
figure(2)
y=w+w2;
plot(t,y)
title(['Added Waves. Frequencies used= ',num2str(f1),' and ',num2str(f2)])
ylabel(['Amplitude= ',num2str(A)])
%Third Graph:
figure(3)
subplot(2,1,1)
plot(t,y)
title(['Composite. Frequencies used= ',num2str(f1),' and ',num2str(f2)])
ylabel(['Amplitude= ',num2str(A)])
subplot(2,1,2)
plot(t(1:1000),w(1:1000)) %Only Graphing 2T
hold on
plot(t(1:1000),w2(1:1000))
hold off
title(['Frequencies used= ',num2str(f1),' and ',num2str(f2)])
ylabel(['Amplitude= ',num2str(A)])
end

Accepted Answer

Star Strider
Star Strider on 1 Aug 2019
Don’t number the figures. They will increment themselves.
Try this:
t=linspace(1,20,10000); %10000 Datapoints
f1=8;
f2=9;
A=1;
w= A*sin(f1*t); %Blue Wave
for f2=[9 9.5 13 15]
w2=A*sin(f2*t); %Red Wave
% First Graph:
figure
plot(t(1:1000),w(1:1000)) %Only Graphing 2T
hold on
plot(t(1:1000),w2(1:1000))
hold off
title(['Frequencies used= ',num2str(f1),' and ',num2str(f2)])
ylabel(['Amplitude= ',num2str(A)])
% Second Graph:
figure
y=w+w2;
plot(t,y)
title(['Added Waves. Frequencies used= ',num2str(f1),' and ',num2str(f2)])
ylabel(['Amplitude= ',num2str(A)])
%Third Graph:
figure
subplot(2,1,1)
plot(t,y)
title(['Composite. Frequencies used= ',num2str(f1),' and ',num2str(f2)])
ylabel(['Amplitude= ',num2str(A)])
subplot(2,1,2)
plot(t(1:1000),w(1:1000)) %Only Graphing 2T
hold on
plot(t(1:1000),w2(1:1000))
hold off
title(['Frequencies used= ',num2str(f1),' and ',num2str(f2)])
ylabel(['Amplitude= ',num2str(A)])
end
The only other change I made was to move ‘w’ outside the loop. There is no need to recalculate it each time if it doesn’t change.

More Answers (0)

Categories

Find more on Line Plots in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!