我的目标是将各种文件夹和文本文件中的数据导入matlab。
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 之类的东西可能吗?