Nozdrum Nozdrum - 1 year ago 72
Python Question

Matlab output matrix to file with a reasonable format

I am writing the representation of an object to file. Its follows this simple format


Now I have multiple matrices to output, but the standard-way looks very ugly

f = open('somefile', 'w+t');
fprintf(f,'%+.4f\n', someObject.size);

But this will just result in an unreadble file like this

size: 5.1234

And so on for hundreds of lines. If I do this in python/numpy
( f.write("size: " + str(someObject.size) + "\n")
I get something readable like

size:[[5.1234 3.1234 2.5421 232322]
[5.1234 3.1234 2.5421 232322]....

It preserves the shape and aligns it properly. How do I do this with matlab.

Answer Source

You need to split the fprintf command. Use an auxilary function:

function numpy_like_fprintf(fid, format_single_element, values)
fprintf(fid, '[');
fprintf(fid, [' ',format_single_element], values);
fprintf(fid, ' ]\n');

Now you can

numpy_like_fprintf(f, '%+.4f', someObject.size);

Alternatively, you can use num2str to convert the array to string, much like python's str().
Note that you can format the way numbers are converted to strings in num2str

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download