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

后端 未结 4 1439
一个人的身影
一个人的身影 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 04:13

    I ran into a similar situation adding a header to a csv. You can use dlmwrite with -append to add a single line by setting your delimiter equal to '' as shown below.

    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
    header1 = 'A, B'
    dlmwrite(fName, str, 'delimiter', '')
    dlmwrite(fName, header1, '-append', 'delimiter', '')
    dlmwrite(fName, mat1, '-append','delimiter', ',')
    

    This produces the following:

    This is the matrix: 
    A, B
    23,46
    56,67
    

提交回复
热议问题