MATLAB: Writing file in matlab with fprintf and dlmwrite in loop.

dlmwritefprintfMATLABtxt

I'm trying to get a loop to write headers between matrices to a .txt file from matlab.
Example code:
filename = 'sampleXLS.dat';
datfile = fopen(filename,'w');
header = 'Header \n';
mat1 = [1,2,3;4,5,6];
mat2 = [7,8;9,10];
mat3 = [11;12;13];
mats = {mat1,mat2,mat3};
for iter = 1:length(mats)
data = mats{iter}
fprintf(datfile, header);
dlmwrite(filename, data,'-append','delimiter',' ','precision', '%f');
end
I want
Header
1 2 3
4 5 6
Header
7 8
9 10
Header
11
12
13
I am getting
Header
Header
Header
3
4 5 6
7 8
9 10
11
12
13
Note the missing 1 and 2, when I step though the file in debug mode it is inserting and replacing the numbers with the headers as it goes along.
Is there a way to tell fprintf to append?

Best Answer

The problem is using the fprintf and dlmwrite together - each behaves differently when writing data to file. See fprintf and dlmwrite for details and examples on their use.
The above code should use the same functions to write the text and numeric data to file. For example, dlmwrite can be used to write matrix to ASCII-delimited file. A text string is still a one-dimensional matrix and so can be written to file using this function (I know the documentation states that only numeric data can be written, but it is possible to write out a string). Just replace
fprintf(datfile, header);
with
dlmwrite(filename,header,'-append','delimiter','');
where
header = 'Header';
(without the new line character).
Else, replace the
dlmwrite(filename, data,'-append','delimiter',' ','precision', '%f');
with
for u=1:size(data,1)
for v=1:size(data,2)
fprintf(datfile,'%f ',data(u,v));
end
fprintf(datfile,'\n');
end
Try either of the above and see what happens!