使用 for 循环读取多个文件
Read multiple files with for loop
我的代码如下。在代码中,我只评估 'fb2010'
文件中的数据。我想添加其他文件“'fb2020'
、'fb2030'
和 'fb2040'
并通过相同的代码评估它们的数据。我的问题是如何应用 for
循环并包含其他数据文件。我试过了,但我被 for
循环弄糊涂了。
load('fb2010'); % loading the data
x = fb2010(3:1:1502,:);
% y_filt = filter(b,a,x); % filtering the received signal
y_filt= filter(b,a,x,[],2);
%%%%%%% fourier transform
nfft = length(y_filt);
res = fft(y_filt,nfft,2)/nfft;
res2 = res(:,1:nfft/2+1); %%%% taking single sided spectrum
res3 = fft(res2,[],2);
for i = 3:1:1500 %%%% dividing each row by first row.
resd(i,:) = res3(i,:)./res3(1,:);
end
我假设您的文件是 MAT 文件,而不是 ASCII。您可以通过 load
return a struct
and using dynamic field referencing:
n = 4;
for i = 1:n
vname = ['fb20' int2str(i) '0']; % Create file/variable name based on index
s = load(vname); % Load data as struct (overwriting previous s)
x = s.(vname)(3:1:1502,:); % Access struct with dynamic field reference
% Rest of your code
...
end
如果您使用的是纯 ASCII 文件,load
不会生成结构。但是,此类文件要简单得多(请参阅 load
/save
的文档)。以下代码可能会起作用:
n = 4;
for i = 1:n
vname = ['fb20' int2str(i) '0']; % Create file/variable name based on index
s = load(vname); % Load data as matrix (overwriting previous s)
x = s(3:1:1502,:); % Directly index matrix
% Rest of your code
...
end
最好将文件扩展名添加到您的 load
命令中,以使您的代码更具可读性。
我的代码如下。在代码中,我只评估 'fb2010'
文件中的数据。我想添加其他文件“'fb2020'
、'fb2030'
和 'fb2040'
并通过相同的代码评估它们的数据。我的问题是如何应用 for
循环并包含其他数据文件。我试过了,但我被 for
循环弄糊涂了。
load('fb2010'); % loading the data
x = fb2010(3:1:1502,:);
% y_filt = filter(b,a,x); % filtering the received signal
y_filt= filter(b,a,x,[],2);
%%%%%%% fourier transform
nfft = length(y_filt);
res = fft(y_filt,nfft,2)/nfft;
res2 = res(:,1:nfft/2+1); %%%% taking single sided spectrum
res3 = fft(res2,[],2);
for i = 3:1:1500 %%%% dividing each row by first row.
resd(i,:) = res3(i,:)./res3(1,:);
end
我假设您的文件是 MAT 文件,而不是 ASCII。您可以通过 load
return a struct
and using dynamic field referencing:
n = 4;
for i = 1:n
vname = ['fb20' int2str(i) '0']; % Create file/variable name based on index
s = load(vname); % Load data as struct (overwriting previous s)
x = s.(vname)(3:1:1502,:); % Access struct with dynamic field reference
% Rest of your code
...
end
如果您使用的是纯 ASCII 文件,load
不会生成结构。但是,此类文件要简单得多(请参阅 load
/save
的文档)。以下代码可能会起作用:
n = 4;
for i = 1:n
vname = ['fb20' int2str(i) '0']; % Create file/variable name based on index
s = load(vname); % Load data as matrix (overwriting previous s)
x = s(3:1:1502,:); % Directly index matrix
% Rest of your code
...
end
最好将文件扩展名添加到您的 load
命令中,以使您的代码更具可读性。