MATLAB: Combine multiple text files into one matrix

multiple text filestext file

Hi all,
I am new to matlab and need some help.
I want to load multiple .txt files (same directory) into one matrix. I have 100 single-column text files with the same number of rows ( = 50). I want to store each file values (column) as a row in the matrix. In the end, I would like to get a matrix with 50 columns and 100 rows.
Thank you!

Best Answer

projectdir = 'directory_name_goes_here';
dinfo = dir( fullfile(projectdir, '*.txt'));
nfiles = length(dinfo);
assert(nfiles == 100, 'expected 100 files');
filenames = fullfile(projectdir, {dinfo.name});
data = zeros(nfiles, 50);
for K = 1 : nfiles
thisfile = filenames{K};
thisdata = load(thisfile);
data(K, :) = thisdata;
end
Caution: if your files are named something like 'data1.txt', 'data2.txt', ... 'data10.txt', 'data11.txt' ... then the above code will not load them in that order: it will load 'data1.txt', 'data11.txt', 'data12.txt', ... 'data2.txt', 'data21.txt', ... See the File Exchange for "natural directory sort"