Importing multiple text files into MATLAB

18 visualizaciones (últimos 30 días)
Akarsh Shetty
Akarsh Shetty el 30 de Jun. de 2022
Comentada: Voss el 22 de Jul. de 2022
I was trying to import and read a series of text files. i was able to read the data for one file at a time. Howevwer while using the array indexing via the for loop, all the files could not be read at once
It gives an error saying
% subscripted assignment dimension mismatch.
p=dir('*.txt');
N=length(p);
for k=1:N
[fid]=fopen(p(k).name,'r');
A(k)=cell2mat(textscan(fid, '%f %f', 'HeaderLines', 4));
fid=fclose(fid);
end

Respuesta aceptada

Voss
Voss el 30 de Jun. de 2022
The options you have available to you depend on the contents of your txt files, but one general option (i.e., will work regardless) is to use a cell array:
p=dir('*.txt');
N=length(p);
A = cell(1,N); % cell array A
for k=1:N
% [fid]=fopen(p(k).name,'r');
fid = fopen(p(k).name,'r');
% A(k)=cell2mat(textscan(fid, '%f %f', 'HeaderLines', 4));
A{k} = cell2mat(textscan(fid, '%f %f', 'HeaderLines', 4)); % use {} for indexing A
% fid=fclose(fid);
fclose(fid);
end
Now each element of A is a cell containing the contents of one txt file. Access those contents again using curly braces {}:
A{1} % contents of the first file
A{2} % contents of the second file
A{end} % contents of the last file
% etc.
  4 comentarios
Akarsh Shetty
Akarsh Shetty el 22 de Jul. de 2022
Thank you! I understood it.
Voss
Voss el 22 de Jul. de 2022
You're welcome!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Data Import and Export en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by