Aquiles Páez
Aquiles Páez

Reputation: 573

Matlab: Using csvimport to read several .csv files with a loop

I want to read several .csv files in a folder with this Matlab function. I have no problem at all reading just one of 'em, but I don't know how to use 'em to read them all at once.

For a simple file, I just did this (I believe it has too many lines, but it works):

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

That works just fine, but, what if I want to read them all at once? I suppose I can use something like this:

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

How can I write that loop's argument? the function csvimport needs to have the name of the file so it can work. How can I extract the name of a file, store it into a matrix, and then use it in csvimport(filename).

Can it be like this?:

csvimport(filename(i));

Is there a way to store all the filenames into a vector and then use it as input for csvimport? I believe that could solve my problem.

Any help you can provide, I'll be glad to know.

First EDIT:

I believe there could be a way using:

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

I'll let you know if it worked out for me.

Upvotes: 0

Views: 529

Answers (1)

Suever
Suever

Reputation: 65430

Yes as you've stated, you want to store the filenames in an array (in this case an array of structures) and then loop through them and call csvimport on each of them.

% 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

You can then access the resulting data within the data variable. Such as:

disp(data{1})

For people who like short things...

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

Upvotes: 1

Related Questions