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