Cumulative sinusoidal wave plotting

2 views (last 30 days)
Question: I have to plot a cosine wave starting from 1 Hz. After plotting 1Hz cosine wave, increase the frequency to 2Hz and add 1Hz and 2Hz together and plot it. This has to be done till 9Hz. For the summation, need to use a 'for loop'.
Here is my attempted code:
f=1;
t=-10:0.1:10;
y2=0; %counter
for i=1:8
y1=sin(2*pi*f*t); %plotting
y3=y2+y1; %summing
y2=y3; %storing the value for next iteration
f=f+1; %increment of f
end
subplot(811)
plot(t,y3(1));
subplot(812)
plot(t,y3(2));
subplot(813)
plot(t,y3(3));
subplot(814)
plot(t,y3(4));
subplot(815)
plot(t,y3(5));
subplot(816)
plot(t,y3(6));
subplot(817)
plot(t,y3(7));
subplot(818)
plot(t,y3(8));
After running the code, it shows no error, but the plots are blank.
  1. I am guessing somehow my loops are getting overwritten. What is the mistake I am doing?
  2. Also, is there any way to implement subplots dynamically so I don't have to write them manually?
If you know any answer/answers to my questions, kindly help. Thank you!

Accepted Answer

Star Strider
Star Strider on 7 Sep 2019
Subscript in the loop, and add the second subscript reference in your plot calls.
Try this:
f=1;
t=-10:0.1:10;
y2=zeros(size(t)); %counter
for i=1:9
y1=sin(2*pi*f*t); %plotting
y3(i,:)=sum([y2; y1]); %summing
y2=y3; %storing the value for next iteration
f=f+1; %increment of f
end
subplot(811)
plot(t,y3(1,:));
subplot(812)
plot(t,y3(2,:));
subplot(813)
plot(t,y3(3,:));
subplot(814)
plot(t,y3(4,:));
subplot(815)
plot(t,y3(5,:));
subplot(816)
plot(t,y3(6,:));
subplot(817)
plot(t,y3(7,:));
subplot(818)
plot(t,y3(8,:));
This appears to do what you describe.
Experiment to get the result you want.
  2 Comments
John Doe
John Doe on 7 Sep 2019
Thanks a lot! It works smoothly.
If you could kindly explain the reasoning of writing these two lines :
  1. y2=zeros(size(t))
  2. y3(i,:)=sum([y2;y1])
Star Strider
Star Strider on 7 Sep 2019
As always, my pleasure!
Sure!
  1. The ‘y2’ vector needs to be the same size as ‘y1’ in order to do the addition. This creates it as such initially.
  2. It is necessary for ‘y3’ to be a row vector, and the sum function by default sums along the first dimension (rows), so that every addition produces a new row vector. Doing a simple addition such as ‘y2+y1’ adds them element-wise only, so as ‘y3’ adds rows, will give an eroneous result. It also results in a matrix of increasing row size, instead of the single row vector desired. (I discovered that when I first ran the code.)

Sign in to comment.

More Answers (0)

Categories

Find more on Line Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!