Reputation: 586
So I have a cell array containing 5 elements. Each element is a n by 6 matrix that looks something like this:
31399.5 24581.8 24083.9 22764.7 22458 15473.5
81169.4 83739.2 82516.1 84139.6 83552.3 55342.7
41356.6 38413.3 37613 34329.8 38681.8 23949.9
For each element in the array, I want to print the corresponding matrix to a text file in the exact same format as above - separating each element of the cell array by a blank line.
Right now I am able to write each element of the cell array to a text file. However, the program doesn't write each row on a new line, it looks more like this:
31399.5 24581.8 24083.9 22764.7 22458 15473.5 81169.4 83739.2 82516.1 84139.6 83552.3 55342.7 41356.6 38413.3 37613 34329.8 38681.8 23949.9
It writes each matrix as a single line. This is my code (labels
is the 1 by 5 cell array):
fid = fopen('labels.txt','wt');
for i = 1:length(labels)
fprintf(fid,'%g\t',labels{i}');
fprintf(fid,'\n');
end
fclose(fid)
How can I modify this so that the data is presented row by row? Any help is highly appreciated.
Upvotes: 2
Views: 91
Reputation: 104503
Using fprintf
to print out matrices is never very friendly. Try using dlmwrite
instead of fprintf
and in the case where you want to append the results to file, use the -append
flag. You'll also want to adjust the precision since dlmwrite
by default rounds numbers. Something like this could work:
for i = 1:length(labels)
dlmwrite('labels.txt', sprintf('Label %d', i), '-append');
dlmwrite('labels.txt', labels{i}, '-append', 'precision', 6);
dlmwrite('labels.txt', ' ', '-append');
end
Take note that I had to do a bit of a hack to perform a carriage return before you write the next matrix for appending. Simply put, I appended a space after the matrix to force a new line when appending. For each carriage return, you're going to see a blank line with one space but I'm assuming this won't be a problem. I've also taken the liberty in adding in Label i
before each matrix where i
is the matrix seen at cell i
.
Upvotes: 2