How do I use a for-loop to do fft and plot the power?
Show older comments
Hello,
I have a data set (time and variable Be) and I want to do a fft on one part of the data at a time (1000 years). To do this, I would like to use a for-loop that plots the power of the period for each of the different ffts. How do I do this? I'm new to Matlab but I have tried the code below:
hold on
for ts=(0:1000:5000)'; % I have data between 0 and 5000 years ago.
A=fft(Be); % Do FFT on the Be data.
A(1)=[];
n=length(A);
power=abs(A(1:floor(n/2))).^2;
nyquist=1/2;
freq=(1:n/2)/(n/2)*nyquist;
period=1./freq;
plot(period,power);
end
When I do this, I get only one plot. What am I doing wrong?
Thanks!
Accepted Answer
More Answers (2)
David Young
on 16 Dec 2014
Edited: David Young
on 16 Dec 2014
The variable Be is not changed between iterations, so A will also be the same each time, so each plot will be the same as the previous one. If Be is a vector with all 5000 data points, then you could replace the first line in the loop with
A = fft(Be(ts+1:ts+999));
to select 1000 data points starting from ts.
4 Comments
Emma
on 17 Dec 2014
Adam
on 17 Dec 2014
I usually prefer to use instructions such as
figure; hAxes = gca;
hold( hAxes, 'on' )
plot( hAxes, period, power )
when dealing with axes as it can be easy to have things go wrong relying on implicit behaviour of the axes you expect being the one currently in focus. That may not be the problem here as your 'plot' instructions should apply to the same axes as your 'hold' instruction.
When you say you have only one plot do you mean you can only see 1 plot or that there is literally just 1 plot in the plot browser? (i.e. has it plotted the same thing 5 times still or has it really only plotted one?).
Incidentally your loop has 6 iterations rather than 5.
Emma
on 17 Dec 2014
Sudharsana Iyengar
on 17 Dec 2014
HI,
Try this and let me know.
for a= 0:4
A=fft(Be(a*1000:(a+1)*1000));
A(1)=[];
n=length(A);
power=abs(A(1:floor(n/2))).^2;
nyquist=1/2;
freq=(1:n/2)/(n/2)*nyquist;
period=1./freq;
figure()
plot(period,power)
end
1 Comment
Emma
on 17 Dec 2014
Categories
Find more on Spectral Analysis 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!