我打算将各种文件夹和文本文件中的数据导入到matlab中。使用cellfun向量化脚本
clear all
main_folder = 'E:\data';
%Directory of data
TopFolder = dir(main_folder);
%exclude the first two cells as they are just pointers.
TopFolder = TopFolder(3:end);
TopFolder = struct2cell(TopFolder);
Name1 = TopFolder(1,:);
%obtain the name of each folder
dirListing = cellfun(@(x)dir(fullfile(main_folder,x,'*.txt')),Name1,'un',0);
Variables = cellfun(@(x)struct2cell(x),dirListing,'un',0);
FilesToRead = cellfun(@(x)x(1,:),Variables,'un',0);
%obtain the name of each text file in each folder
这提供了'main_folder'内每个文件夹中每个文本文件的名称。我现在试图加载数据而不使用for循环(我意识到for循环有时会更快,但我正在瞄准一个紧凑的脚本)。
我会使用的方法for循环将是:
for k = 1:length(FilesToRead);
filename{k} = cellfun(@(x)fullfile(main_folder,Name{k},x),FilesToRead{k},'un',0);
fid{k} = cellfun(@(x)fopen(x),filename{k},'un',0);
C{k} = cellfun(@(x)textscan(x,'%f'),fid{k},'un',0);
end
是否有这不会使用循环在所有涉及到的方法? cellfun内的cellfun可能吗?
我同意,环路版本似乎是方式更紧凑。 – Emma 2012-04-13 11:07:55