For loop of an FFT script

2 views (last 30 days)
Hussein Kokash
Hussein Kokash on 1 Nov 2022
Edited: CHIRANJIT DAS on 1 Nov 2022
Hello,
I have a script that works for a single file using dlmread, the output seems to work fine. I need to put it inside a loop but I am getting some errors.
Here is the scipt for a single file:
z = data(:,1);
y = data(:,2);
T=data(:,3);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% % fft method
[fhz,fft_spectrum] = do_fft(z(:),y(:));
[amplitude1, idx] = max(fft_spectrum);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
L = length(z);
fs = 1/mean(diff(z)); % Sampling Frequency
fn = fs/2; % Nyquist Frequency
yc = y - mean(y); % Sampling Interval
FTv = fft(yc)/L; % Fourier Transform
Fv = linspace(0, 1, fix(L/2)+1)*fn; % Frequency Vector
Iv = 1:length(Fv); % Index Vector
[max_FTv, maxidx] = max(FTv(Iv));
Fv_at_max_FTv = Fv(maxidx);
wavelength1=1/Fv_at_max_FTv;
Any help would be appreciated, thanks!

Accepted Answer

CHIRANJIT DAS
CHIRANJIT DAS on 1 Nov 2022
Edited: CHIRANJIT DAS on 1 Nov 2022
@Hussein Kokash Not sure whether your files are located in a single folder or not. If it is in single folder then you can make use of below code..
loc='/Volumes/Backup Plus/path/'; % put path of your data files
cd(loc)
fnames=dir(fullfile('*.txt')); % Put the extension of your files
output=[];
for i=1:numel(fnames)
filename=fnames(i).name;
data = dlmread(filename) % I would suggest you to use readmatrix instead of dlmread.
z = data(:,1);
y = data(:,2);
T=data(:,3);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% % fft method
[fhz,fft_spectrum] = do_fft(z(:),y(:));
[amplitude1, idx] = max(fft_spectrum);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
L = length(z);
fs = 1/mean(diff(z)); % Sampling Frequency
fn = fs/2; % Nyquist Frequency
yc = y - mean(y); % Sampling Interval
FTv = fft(yc)/L; % Fourier Transform
Fv = linspace(0, 1, fix(L/2)+1)*fn; % Frequency Vector
Iv = 1:length(Fv); % Index Vector
[max_FTv, maxidx] = max(FTv(Iv));
Fv_at_max_FTv = Fv(maxidx);
wavelength1=1/Fv_at_max_FTv;
output=[output;wavelength1];
end
If you want to save wavelength, then you can find it in output. You can save your desire outputs this way.

More Answers (0)

Categories

Find more on Fourier Analysis and Filtering in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!