Help with saving a matrix
3 次查看(过去 30 天)
显示 更早的评论
I have a matrix with dimension MxN double. How can I write this matrix in a .dat file by using the function fprintf ? M and N can be arbitrarily big. Thanks
采纳的回答
Stephen23
2015-3-18
编辑:Stephen23
2015-3-19
Rather than creating some hack-code to do this using fprintf, why not using one of the inbuilt function that prints the whole matrix at once: csvwrite or dlmwrite. These will automatically print the whole of your matrix, regardless of how large the size. dlmwrite can even be used to append data to the end of a file.
Here is an example showing how simple it is to use dlmwrite:
>> A = rand(4,5);
>> dlmwrite('test.csv',A)
or with a specific precision:
>> dlmwrite('test.csv',A,'precision','%.3f')
1 个评论
dpb
2015-3-18
???
fprintf is vectorized; see following answer.
Granted some of the higher level functions are a little more convenient, but really not all that much difference...the key one is probably that can specify a specific single format string and the \n is automagically appended.
更多回答(1 个)
dpb
2015-3-18
编辑:dpb
2015-3-18
Hmmm....answering my own question--ok, they are a little skimpy on generalities, aren't they?
fmt=['%.3f ',1,size(X,2)-1) '%.3f\n']; % format for number columns
fprintf(fid,fmt,X.') % and write--NB: the .' to output in row order
open the file with fopen first, of course, to have a valid file handle and close when done.
NB: There are higher-level routines such as dlmwrite that relieve some of the burdens. A particular key of note in the above is the use of repmat to build the format string of the right number of repeated fields since C i/o is so lame-brained/ill-conceived as to have written the descriptors such that can't introduce a repeat count (can you tell I've been thru another extensive thread just within last few days lamenting many of the shortcomings of C format strings vis a vis Fortran FORMAT?)...
I agree after looking that the examples should be more representative of real practice for more than toy ones that illustrate such issues and mention the storage order issues, etc., etc., etc., ...
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!