Matlab:使用csvimport通过循环读取几个.csv文件

时间:2016-02-24 01:15:10

标签: matlab csv

我想在这个Matlab function的文件夹中阅读几个.csv文件。我没有任何问题只是阅读其中一个,但我不知道如何使用'em一次性阅读它们。

对于一个简单的文件,我刚刚做了这个(我相信它有太多行,但它有效):

mkdir('Unzipped')  % create a new folder
% Choosing a file to unzip
[filename, pathname] = uigetfile('*.zip', 'Select a compressed file'); 
if isequal(filename,0)
   disp('User selected Cancel')
else
   disp(['User selected ', fullfile(pathname, filename)])
   filename=fullfile(pathname, filename);
   unzip(filename, 'Unzipped');
end
%To choose the .csv file I want to read, I use this.

[filename, pathname] = uigetfile({'*.csv'}, 'Select a .csv file');
if isequal(filename,0)
   disp('User selected Cancel')
else
   disp(['User selected ', fullfile(pathname, filename)])
   filename=fullfile(pathname, filename);
   csvimport(filename);
end

这很好,但是,如果我想一次阅读它们怎么办?我想我可以使用这样的东西:

files= dir('folder where files are stored\*.csv');      
num_files = length(files);
for i=1:num_files
     % MY DOUBT IS HERE
end

如何编写该循环的参数?函数csvimport需要具有文件名,以便它可以工作。如何提取文件名,将其存储到矩阵中,然后在csvimport(filename)中使用。

可以这样吗?:

csvimport(filename(i));

有没有办法将所有文件名存储到一个向量中,然后将其用作csvimport的输入?我相信这可以解决我的问题。

您可以提供任何帮助,我很高兴知道。

首次编辑:

我相信可以采用以下方式:

allFiles = dir( 'your folder' );
allNames = { allFiles.name };

我会告诉你它是否适合我。

1 个答案:

答案 0 :(得分:1)

是的,正如您所说,您希望将文件名存储在数组中(在本例中为结构数组),然后循环遍历它们并在每个文件上调用csvimport

% Get an array of all files
basepath = 'folder where files are stored';
files = dir(fullfile(basepath, '*.csv'));

% Pre-allocate data storage
data = cell(size(files));

% Import each file using it's filename
for k = 1:numel(files)
    data{k} = csvimport(fullfile(basepath, files(k).name));
end

然后,您可以访问data变量中的结果数据。如:

disp(data{1})

对于那些喜欢简短的人......

data = arrayfun(@(f)fullfile(basepath,f.name), dir(fullfile(basepath,'*.csv')), 'uni', 0);
相关问题