How to write data in an appointed data format?

3 次查看(过去 30 天)
Dear colleagues,
I have a column data:
44566
44567
44568
44565
44566
4565
44563
99999
44561
44563
44564
...
but I want to convert my data into the following data format, e.g., 6f12.4 would imply six values per row each twelve characters long with four decimal places.
4565.000 44566.000 44567.000 44568.000 44565.000 44566.000
4565.000 44563.000 99999.000 44561.000 44563.000 44564.000
.....
Could you give me some good suggestions? Many thanks!
  3 个评论
Kathleen
Kathleen 2016-2-17
编辑:Kathleen 2016-2-17
Thanks for your comment! "Twelve characters" is Fortran format such as 6f12.4. No, I also have the real numbers.
Could you give me some advices and help?
Star Strider
Star Strider 2016-2-17
My pleasure!
It works essentially the same way in MATLAB, but the format is more like C than FORTRAN, even though MATLAB began as FORTRAN-based. For details on the various format descriptors, see the documentation for the fprintf function.
To do the equivalent of 6F12.4 in FORTRAN with the ‘newline’ characters as well, in MATLAB it’s useful to use the repmat function. For instance, your format and print statements would be:
fmt = [repmat('%12.4f\t', 1, 5) '%12.4f\n'];
fprintf(fid, fmt, v);
I broke these out into two lines to (1) demonstrate that it is possible, and (2) demonstrate alternate ways to repeat format descriptors in MATLAB.
The tab characters ('\t') are necessary in MATLAB if you want to read the file easily, because one shortcoming in MATLAB file read capability is the inability to specify precise column field widths, so a line such as:
3.1415E+005-1.2345E-010
completely eludes MATLAB, and requires special reading and parsing to eventually dissect it into 3.1415E+005 and -1.2345E-010 that would be easily read in FORTRAN. May be someday MATLAB will have that capability built-in.

请先登录,再进行评论。

采纳的回答

Star Strider
Star Strider 2016-2-17
It would imply that in FORTRAN but not MATLAB.
You would have to do something like this:
v = [44566
44567
44568
44565
44566
4565
44563
99999
44561
44563
44564
44567];
fid = 1; % Here ‘1’ Is ‘stdout’, The Command Window, But You Would Use The ‘fopen’ Function To Write To A File
fprintf(fid, '%12.4f\t%12.4f\t%12.4f\t%12.4f\t%12.4f\t%12.4f\n', v)
producing:
44566.0000 44567.0000 44568.0000 44565.0000 44566.0000 4565.0000
44563.0000 99999.0000 44561.0000 44563.0000 44564.0000 44567.0000

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Fortran with MATLAB 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by