2017-09-13 135 views
-1

我有下面的代码在MATLAB如何在MatLab中加载多个文件?

filename='1'; 
filetype='.txt'; 
filepath='D:\20170913\'; 
fidi = fopen(strcat(filepath,filename,filetype)); 
Datac = textscan(fidi, repmat('%f', 1, 640), 'HeaderLines',1, 
'CollectOutput',1); 
f1 = Datac{1}; 
sum(sum(f1)) 

我如何可以加载多个文件来加载一个矩阵文件,说1-100。 在此先感谢。

+1

添加一个for循环? – 10a

回答

0

只需在for循环中包含所有内容,即从1循环到N_files,这是您拥有的文件数。我使用函数num2str()将索引i转换为字符串。我还将矩阵求和包含在一个数组file_sums和一个loaded_matrices单元格数组中,用于存储所有加载的矩阵。如果所有加载的矩阵具有已知且相同的维度,则可以使用二维数组(例如loaded_matrices = zeros(N_rows,N_columns,N_files);然后将数据加载为loaded_matrices(:,:,i)= Datac {1 };)。

% N_files - the number of files that you have 
N_files = 100; 
file_sums = zeros(1,N_files); 
loaded_matrices = cell(1,N_files); 
for i=1:1:N_files 
    filename=num2str(i); 
    filetype='.txt'; 
    filepath=''; 
    fidi = fopen(strcat(filepath,filename,filetype)); 
    Datac = textscan(fidi, repmat('%f', 1, 640), 'HeaderLines',1,... 
     'CollectOutput',1); 
    loaded_matrices{i} = Datac{1}; 
    file_sums(i) = sum(sum(loaded_matrices{i})); 
end