Importing multiple text files into MATLAB

57 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Voss
Voss il 30 Giu 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 Commenti
Akarsh Shetty
Akarsh Shetty il 22 Lug 2022
Thank you! I understood it.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Shifting and Sorting Matrices in Help Center e File Exchange

Prodotti


Release

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by