【问题标题】:How to save several times without overwriting the file如何保存多次而不覆盖文件
【发布时间】:2019-09-20 20:13:07
【问题描述】:

我在 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

【问题讨论】:

  • 要么附加到文件(参见链接的文档@AnderBiguri),要么在每次循环迭代时创建一个新文件。
  • 如果您要保存 matix,请改用 save... 写入文本文件不是最佳选择,除非您必须这样做
  • 代码没有意义,您打开文件进行读取,然后写入它们。我敢肯定你一定是在那儿遇到了错误。

标签: matlab save overwrite


【解决方案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

【讨论】:

    猜你喜欢
    • 2018-02-18
    • 2019-10-10
    • 2018-08-22
    • 2019-02-28
    • 1970-01-01
    • 2012-05-11
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多