Importing multiple text files into MATLAB
57 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
Voss
le 30 Juin 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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!