How can I write strings and matrices to a .txt file in MATLAB?

后端 未结 4 1437
一个人的身影
一个人的身影 2021-02-06 03:16

I need to write data to a .txt file in MATLAB. I know how to write strings (fprintf) or matrices (dlmwrite), but I need something that can do

4条回答
  •  轮回少年
    2021-02-06 03:54

    I think all you have to do to fix your problem is add a carriage return (\r) to your FPRINTF statement and remove the first call to DLMWRITE:

    str = 'This is the matrix: ';      %# A string
    mat1 = [23 46; 56 67];             %# A 2-by-2 matrix
    fName = 'str_and_mat.txt';         %# A file name
    fid = fopen(fName,'w');            %# Open the file
    if fid ~= -1
      fprintf(fid,'%s\r\n',str);       %# Print the string
      fclose(fid);                     %# Close the file
    end
    dlmwrite(fName,mat1,'-append',...  %# Print the matrix
             'delimiter','\t',...
             'newline','pc');
    

    And the output in the file looks like this (with tabs between the numbers):

    This is the matrix: 
    23  46
    56  67
    


    NOTE: A short explanation... the reason for needing the \r in the FPRINTF statement is because a PC line terminator is comprised of a carriage return followed by a line feed, which is what is used by DLMWRITE when the 'newline','pc' option is specified. The \r is needed to ensure the first line of the matrix appears on a new line when opening the output text file in Notepad.

提交回复
热议问题