MATLAB: Cumulative sinusoidal wave plotting

for loopMATLABplottingsubplotwavelet

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!

Best Answer

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.