MATLAB Answers


How can I use fprintf to print an mxn matrix of values to a file

Asked by Thomas Burbey on 19 Sep 2019 at 18:26
Latest activity Commented on by Star Strider
on 20 Sep 2019 at 13:56
I have a calculated flow net of values in a matrix that I want to print in order (mxn)
How can I print the matrix to a file that has the matrix (rows x cols) in order. How would I do this using fprintf since I don't see any way to repeat using this function.


Sign in to comment.


1 Answer

Answer by Star Strider
on 19 Sep 2019 at 19:34
 Accepted Answer

There are a numberr of ways to write your matrix, depending on what you want to do.
Since you want to use fprintf, if ‘M’ is your matrix:
fid = fopen( ... , 'wt')
fprintf(fid, [repmat('%10.5f\t', 1, size(M,2)) '\n'], M') % Note Transpose Operation
That should work. Experiment to get the result you want.


Pay attention to the ' after the M at the end of the second line: it is important to get this to work.
Personally I would use .' instead of ' since ' by itself is conjugate transpose. There would be no difference to the output as fprintf() always ignores the imaginary part of values anyhow, but ' is unnecessary work compared to .' IMHO.
Thank you. It works!
As always, my pleasure!

Sign in to comment.