MATLAB: Merging Multiple text files

asciifilenamesMATLABmergenatsortnatsortfilesnatural order sort

I have 1505 text files, each 96×6. I want to be able to merge them such that file 2 is below file 1, file 3 is below file 2 etc all in the same text file.
I was previously given this code
files=dir('*.txt');
fileout='merged.txt';
fout=fopen(fileout,'w');
for cntfiles=1:length(files)
fin=fopen(files(cntfiles).name);
while ~feof(fin)
fprintf(fout,'%s %d\n',fgetl(fin),cntfiles);
end
fclose(fin);
end
fclose(fout);
At first it seemed to work but I found it jumbles the data a bit and I cannot use it.
Are there any alternatives?

Best Answer

I had exactly the same issue, and solved it by writing a function called natsortfiles to sort file-names into order based on their number values (not just ASCII order). You can get it here:
S = natsortfiles(dir(..));
You can use it with your code by doing something like this (outline only):
S = dir('*.txt');
S = natsortfiles(S); % alphanumeric sort by filename
for k = 1:numel(S)
fid = fopen(S(k).name,'rt');
... code here
fclose(fid);
end