如何保存几次而不覆盖文件

时间:2019-05-02 10:12:45

标签: matlab save overwrite

我在matlab中的代码有问题。 我有一个矩阵C(将整形作为矢量),我想将多个C矢量保存到一个文件中。这是我的代码

wynik = reshape(C',1,[]);
    fileID = fopen('Desktop\test.txt','r');
    fileID_out = fopen('Desktop\test_out.txt','r');

  fprintf(fileID, '%d \r', wynik);
  fprintf(fileID, '\n');
  fprintf(fileID_out, ' %d \r\n', 2);
 end 

我在一开始就做了一个循环,所以在控制台中我有例如2个不同的矩阵,但是使用此代码,它会覆盖我的文件,而我只保存最后一个向量。我想要这样的东西(简短示例) A = [1 2 3; 4 5 6](第一个循环) A = [7 8 9; 1 2 3](第二个循环) 在我的文件中(值之间有空格,并且在行尾带有\ n):

1 2 3 4 5 6
7 8 9 1 2 3

1 个答案:

答案 0 :(得分:1)

问题中的示例非常不清楚,因为您询问有关保存数据,但是所有文件打开说明仅使用读取权限。

我将为您提供一个示例,该示例适用于您的第二个(较短的)示例,因为它可以使您更清楚地实现目标。

我强烈建议您阅读以下文档:

  • fopen,尤其是参数permission的用法。
  • fprintf,参数formatSpec将很有用。

借助该文档,您将认识到写入已包含数据的现有文件称为对该文件的 append 。因此,供您使用:首次创建文件时,请以权限'w'打开该文件。对于您要添加(= 附加 )文件的所有其他时间,请以'a'权限打开它,然后正常写入。

您的第二个示例代码:

%% Initial data
A = [1,2,3;4,5,6];

%% prepare format specifier for a complete line
nElem = numel(A) ;
baseformat = '%d ' ;                                % base number format
writeFormat = repmat( baseformat , 1 , nElem ) ;    % replicated "nElem" times
writeFormat = [writeFormat(1:end-1) '\n'] ;         % remove last trailing space and replace by newline
% => now writeFormat = "%d %d %d %d %d %d\n"

%% Open the file the first time to write the first line
% permission 'w' => Open or create new file for writing. Discard existing contents, if any.
fidout = fopen('myfileout.txt', 'w') ; 
fprintf( fidout , writeFormat , A(:) ) ;
fclose(fidout) ;

%% Now let's write 5 additional lines
for iLine=1:5
    % simulate a different matrix [A]
    A = A + nElem ; % A will continue counting

    % permission 'a' => Open or create new file for writing. Append data to the end of the file.
    fidout = fopen('myfileout.txt', 'a') ; 
    fprintf( fidout , writeFormat , A(:) ) ;
    fclose(fidout) ;
end

应该给您文件myfileout.txt,其中应包含:

1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36
相关问题