MATLAB: Simultaneously Merging and Editing multiple text files

edit loaded datamerge files

I need to do two simple tasks, but am having trouble combining them. First, I need to combine multiple text files into a single file. Second, I need to add a column to each of the text files prior to combining. For example, I have 3 different subjects, all of whom have nearly identical but separate text files. The files are all a few hundred rows long, but only 4 columns wide. The exact same column names (i.e. variables) are recorded for each subject/files. But, because the contents of the text files are identical, before I combine them into a single file, I need to add a variable/column to identify which file is which in the biglist.
I'm stuck at two points. 1) When I run the loop to read the data into MatLab (in order to edit and re-paste it all together), each subsequent text file is overriding the previous so I only end up with the final data file entered. I've tried to rename the data on each loop and store it to later concatenate, but it doesn't like me. See below
startSubj = 1;
endSubj = 3;
for a = startSubj:endSubj
textFileName = ['Subject' num2str(a) '.txt.']
fid = fopen(textFileName, 'r');
data = textscan(fid, '%n%n%n%n', 'headerlines', 1);
fclose(fid)
end
The second point I'm stuck is editing each data file to add a column before merging. Part of the problem is that I am not well versed in matlab and thus, unable to edit anything that isn't already a matrix (which the fopen command doesn't appear to give).
Help on any/all of the question is appreciated!

Best Answer

This will merge all text files (no matter what the content is) and add the file number.
files=dir('part*.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);