Borrar filtros
Borrar filtros

For loop to read in sequentially named .txt files

1 visualización (últimos 30 días)
HC98 el 6 de Dic. de 2021
Comentada: Alagu Sankar Esakkiappan el 9 de Dic. de 2021
I have a batch of txt files named "0, 2, 4, 6, 8".txt and wondered if there was a way for me to read them all in as one batch using a for loop, maybe something like:
txtFiles = dir('*.txt') ;
N = length(txtFiles) ;
iwant = cell(1,N) ;
for i = 1:N
iwant{i} = importdata(txtFiles(i).name) ;
% works if all cells are of same size
M = cell2mat(iwant) ;
pcolor(M) ;
shading interp
  1 comentario
Rik el 6 de Dic. de 2021
That code looks like it should work. What happened when you tried it?

Iniciar sesión para comentar.

Respuestas (1)

Alagu Sankar Esakkiappan
Alagu Sankar Esakkiappan el 9 de Dic. de 2021
Editada: Alagu Sankar Esakkiappan el 9 de Dic. de 2021
I gather that you're trying to convert numerical data from many text files into a single matrix. The Code given in question's reference would work fine with a slight catch. I presume that you're trying to concatenate data from all text file sources in a Row-by-Row manner. But with the above code, cell2mat function appends in a columnwise manner. i.e, cell2mat combines three 5*3 cell arrays into a single 5*9 array instead of 15*3 array. To resolve this, You may try transposing the cell array before matrix conversion according to the following reference:
M = cell2mat(iwant') ; % Transpose Cell Array before conversion
You might also run into another problem for matrix conversion if the text files also have a Column text header in each file. In this case, cell2mat will not return a numerical matrix as expected but instead returns a structure. You may extract data in such case using the following reference:
for i = 1:N
iwant{i} = importdata(txtFiles(i).name) ; % iwant now contains Column header text data as well
iwantStruct = cell2mat(iwant'); % Returns a Structure instead of a matrix
matrixData = vertcat(iwantStruct(1:N).data); % Perform Columnwise concatenation to extract data from Stucture for each file
  2 comentarios
Rik el 9 de Dic. de 2021
The second loop can be replaced by this:
That avoids the iterative growing of the array as well.
Alagu Sankar Esakkiappan
Alagu Sankar Esakkiappan el 9 de Dic. de 2021
Good catch! Thanks for the improvement. I have integrated this in my answer as well

Iniciar sesión para comentar.


Más información sobre MATLAB 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