使用for循环

时间:2015-08-03 19:00:25

标签: matlab loops data-processing

我的代码如下。在代码中,我只评估'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

1 个答案:

答案 0 :(得分:0)

我假设您的文件是MAT文件,而不是ASCII。您可以load返回struct并使用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命令以使代码更具可读性是一个好主意。