Reputation: 305
I am writing several lines to a text file, among which is a matrix. I decided to use fprintf for the normal text messages and to use dlmwrite for writing the matrix to the file. However, this action is done in a while loop. Here is the outline:
k=0;
while (k<10):
fprintf(file,'%s', 'Hello');
dlmwrite(file,M ,'-append', 'newline', 'pc');
fprintf(file, '%s' , 'Goodbye');
k= K+1;
however, when I open the file, all the matrices are appended to the very end of the text file instead of each being between a hello and a goodbye. Is there a way to fix this issue?
Upvotes: 2
Views: 8575
Reputation: 61
It may have something to do with the -append
option, that according to the help appends the result to the end of the file.
You are accessing the same file with two functions, fprintf
and dlmwrite
.
This is probably not efficient, but closing the file after every write from fprintf
would work:
clear all
close all
file_name = 'aa.txt';
file = fopen(file_name, 'w');
fclose(file);
file = fopen(file_name, 'a');
M = randn(5);
for kk = 1:10
file = fopen(file_name, 'a');
fprintf(file, 'Hi\n');
fclose(file);
dlmwrite(file_name, M ,'-append', 'newline', 'pc');
file = fopen(file_name, 'a');
fprintf(file, 'Bye\n');
end
If not, just try to print the matrix with other funcion that you create and that uses the same file handler as fprintf
.
Upvotes: 3
Reputation: 17025
use this:
k=0;
file = fopen('exp.txt','a');
while (k<10)
fprintf(file,'%s', 'Hello');
dlmwrite('exp.txt',A ,'-append', 'roffset', 1, 'delimiter', ' ')
fprintf(file, '%s\n' , 'Goodbye');
k= k+1;
end
Upvotes: 4