MATLAB: How to append text to a number matrix for export to .txt tab delimited or ASCII file? fprintf is blowing the mind!

dlmwritefprintftxt

Hello,
I would like to read in an existing text file, remove a row, then add two header rows to the number matrix and finally export/save/print it to an .txt or ASCII file. So far I have this to read in my numbers from a text file:
%%%%



nCols = 125;
format = repmat('%f', [1 nCols]);
fileID = fopen('07N15_T70_Naive_P7sd.txt');
C = textscan(fileID, format, 'HeaderLines',1,'Delimiter','\t');
fclose(fileID);
for i = 1:124; %124 electrodes
forBESA (i,:) = C{1,i};
end
%%%%%
This works fine and I get my number matrix (.txt file is attached).
What I would like to do then is to add two header lines of text to the number matrix. I made these cell arrays:
%%%%
Head1={'TimePoin','ts=750','Channe','ls=124','BeginSwe','ep[ms]=-','1500','Samplin','gInterva','l[ms]=4.','0','Bins/uV=','1'};
Head2 = {'E1','E2','E3','E4','E5','E6','E7','E8','E9','E10','E11','E12','E13','E14'};
%%%%
Then I tried many combinations of
%%%%
dlmwrite('forBESA.txt', Head1 ,'delimiter', '\t')
dlmwrite('forBESA.txt', Head2 , '-append','delimiter', '\t')
dlmwrite('forBESA.txt', forBESA, '-append','delimiter', '\t')
to absolutely no avail. The format of the headers in the cell array is not preserved.
I have been investigating fprintf and think it could work, but I can't seem to get the formatting right.
Thank you in advance.
Gabriella Musacchia Montclair State U NJ

Best Answer

nCols = 125;
format = repmat('%f', [1 nCols]);
fileID = fopen('07N15_T70_Naive_P7sd.txt');
C = textscan(fileID, format, 'HeaderLines',1,'Delimiter','\t');
fclose(fileID);
for i = 1:124;
%124 electrodes for
BESA (i,:) = C{1,i};
end
Head1='TimePoin','ts=750','Channe','ls=124','BeginSwe', ...
'ep[ms]=-','1500','Samplin','gInterva','l[ms]=4.','0','Bins/uV=','1'};
Head2 = {'E1','E2','E3','E4','E5','E6','E7','E8','E9','E10','E11','E12','E13','E14'};
...
Then I tried many combinations of dlmwrite (...
As the doc's say for dlmwrite it doesn't handle anything but a matrix M as output; no cell arrays or cell strings allowed. Pity, but's that the way it is.
fprintf is it; there's an example of a small table in the Examples in the doc for it.
For your case it's the same idea just more fields...
fmt=[repmat('%10s',1,nCols) '\n']; % the eight chars plus a couple spaces
fprintf(fid,fmt,Head1{:}) % and write them
ditto for second header and then follow up w/ appropriate format string for the array. You may want to adjust the spacing of the shorter to center better in the field widths but that's all just bookkeeping (albeit somewhat tedious).