How do I use a for-loop to do fft and plot the power?
显示 更早的评论
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!
采纳的回答
更多回答(2 个)
David Young
2014-12-16
编辑:David Young
2014-12-16
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 个评论
Emma
2014-12-17
Adam
2014-12-17
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
2014-12-17
Sudharsana Iyengar
2014-12-17
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
类别
在 帮助中心 和 File Exchange 中查找有关 Spectral Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!