2

我在一个文本文件中写了几行,其中有一个矩阵。我决定将 fprintf 用于普通文本消息,并使用 dlmwrite 将矩阵写入文件。但是,此操作是在 while 循环中完成的。这是大纲:

 k=0;

 while (k<10):

     fprintf(file,'%s', 'Hello');

     dlmwrite(file,M ,'-append', 'newline', 'pc');

     fprintf(file, '%s' , 'Goodbye');

     k= K+1;

但是,当我打开文件时,所有矩阵都附加到文本文件的最后,而不是每个矩阵都在你好和再见之间。有没有办法解决这个问题?

4

2 回答 2

4

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
于 2013-02-14T17:57:05.010 回答
3

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.

于 2013-02-14T17:57:28.673 回答