Script help: Import several .txt files into a single data matrix

3 views (last 30 days)
Hi there,
I have limited knowledge on scripting but know that loops are very powerful tools that will save me days of time.
I currently require a script that can take a 300*1 (300 lines in one column) of text from a plain .txt file and can upload it into an array that has 168 columns, one for each file, forming a 300*168 array. The files must be in order (currently named #_meants.txt, but the numbers are not sequential) when uploaded. Could anyone point me in the right direction?
Many Thanks

Answers (2)

Michael Haderlein
Michael Haderlein on 28 Jul 2014
First, you need to get the file names:
files=dir('*_meants.txt');
If necessary, you order them by
[~,ind]=sort({files.name});
files=files(ind);
If possible, you can initialize your matrix:
values=zeros(300,length(files));
Then, you indeed need a loop going through the files:
for cnt=1:length(files)
values(:,cnt)=dlmread(files(cnt).name);
end

dpb
dpb on 28 Jul 2014
d=dir('*.txt');
a=zeros(300,length(d)); % use given known size; if unknown read first outside loop
for i=1:length(d)
a(:,1)=importdata(d(i).name);
end
If the returned alphanumeric order isn't as needed, couple of choices --
a) sort the directory names as wanted, or
b) create a secondary file that has the list of names in desired order and traverse it instead of the directory.
for more options but I'm terribly fond of the dir solution if at all possible--it's just so much cleaner...

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!