Writing file in matlab with fprintf and dlmwrite in loop.

5 views (last 30 days)
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?

Accepted Answer

Geoff Hayes
Geoff Hayes on 22 Jul 2014
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!
  2 Comments
Devon
Devon on 22 Jul 2014
Thank you very much! Both options worked! I timed both and apparently the double loop ran faster than the dlmwrite.
Geoff Hayes
Geoff Hayes on 22 Jul 2014
Glad it helped. Interesting timing results which may be due to each dlmwrite call opening and closing the file.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!