2017-09-13 140 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