Cumulative sinusoidal wave plotting
    10 visualizzazioni (ultimi 30 giorni)
  
       Mostra commenti meno recenti
    
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. 
- I am guessing somehow my loops are getting overwritten. What is the mistake I am doing?
- 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!
0 Commenti
Risposta accettata
  Star Strider
      
      
 il 7 Set 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 Commenti
  Star Strider
      
      
 il 7 Set 2019
				As always, my pleasure!  
Sure!  
- The ‘y2’ vector needs to be the same size as ‘y1’ in order to do the addition. This creates it as such initially.
- 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.)
Più risposte (0)
Vedere anche
Categorie
				Scopri di più su Subplots in Help Center e File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

