Importing multiple text files into MATLAB

19 views (last 30 days)
Akarsh Shetty
Akarsh Shetty on 30 Jun 2022
Commented: Voss on 22 Jul 2022 at 16:48
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

Accepted Answer

Voss
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

Sign in to comment.

More Answers (0)

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by