Importing multiple text files into MATLAB
45 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Voss
on 30 Jun 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 Comments
More Answers (0)
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!