Borrar filtros
Borrar filtros

Read multiple .CSV files with csvread using a for loop

26 visualizaciones (últimos 30 días)
Jorge Mira Pérez
Jorge Mira Pérez el 24 de Mzo. de 2018
Comentada: Gershon Koral el 6 de Oct. de 2021
Hello all, I'm have some trouble developing an algorithm to read multiple files at once and store them in different matrices. Heres a little, but sufficient, description of the problem:
Say I have n files named i_p.CSV, where n is a large enough number to do this procedure manually and i is a number that goes from 1 to n. The file i_p.CSV is a csv file with three columns, so what I would end up have on MATLAB is a matrix called data_i, which would be a (m x 3) matrix, where m is also a very large number.
Any tips on how to proceed?

Respuesta aceptada

dpb
dpb el 24 de Mzo. de 2018
d=dir('*_p.clv'); % dir struct of all pertinent .csv files
n=length(d); % how many there were
data=cell(1,n); % preallocate a cell array to hold results
for i=1:n
data(i)=csvread(d(i).name); % read each file
end
Now, iff every one of the n .csv files has the same number of rows you can convert to an array...
data=cell2mat(data);
If they aren't all the same length you'll have to augment the shorter to the length of the longest or truncate the longer to that of the shortest.
  8 comentarios
dpb
dpb el 14 de Feb. de 2020
No truly practical way to skip the last line; simply delete it from the read array after reading the file.
Gershon Koral
Gershon Koral el 6 de Oct. de 2021
This answer is incorrect. The for loop should rather read:
data{i} = csvread(d(i).name);

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre File Operations en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by