Looping Through and Writing into Matrix
9 views (last 30 days)
Show older comments
I'm trying to solve a problem I think it simple but don't seem to get how to do it in Matlab. My other option would be to use MathCad to figure it out.
I have a time series that I want to take the FFT of over various chunks. I want to automate the sequence so I don't have to write n identical command lines for it. Let's say the times series is called SING. I can write:
n=1024
fft1=fft(SING(1:1024),n)/n
The next sets would be
fft2=fft(Sing(1025:2048),n)/n
fft3=fft(Sing(2049:3072),n)/n
etc...
How to I loop things so that I get 3 fft vectors spit out by using a for-loop or some other loop?
Then I want each one of those fft vectors to go into one matrix or be able to automate their average without having to create that matrix myself by appending one vector to another?
Any bit will help. Thanks.
0 Comments
Accepted Answer
Wayne King
on 3 Nov 2011
Hi, you have a couple options. spectrogram() will do what you want if you choose the window length correctly and set the NOVERLAP to 0.
x = randn(16384,1);
S = spectrogram(x,1024,0,1024);
You can also provide the sampling frequency and output frequency and time vectors as well as the short-time periodograms.
The other thing you can do is simply reshape x into columns using reshape() and then apply fft() to the matrix. fft() will be applied to the columns of the matrix.
x = rand(16384,1);
x = reshape(x,1024,16);
xdft = fft(x);
Note that spectrogram returns the one-side spectral estimates (513x1 vectors in this case), while fft() returns the two-sided (1024x1).
2 Comments
Walter Roberson
on 3 Nov 2011
Ah, for some reason I thought fft did not handle matrices, but I see now in the documentation that it does, processing them column by column.
More Answers (1)
Walter Roberson
on 3 Nov 2011
numchunks = floor(length(SING)/n);
chunks = reshape(SING(1:n*numchunks),n,[]);
fftresults = zeros(size(chunks));
for K = 1 : numchunks
fftresults(:,K) = fft(chunks(:,K));
end
avgfft = mean(fftresults,2);
Note that this throws away any remainder of SING that is not enough to fill an entire chunk of length n. Doing things that way makes it easy to make sense of the average fft; trying to incorporate a partial chunk gets a bit messy.
0 Comments
See Also
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!