How to write data in an appointed data format?

조회 수: 3 (최근 30일)
Kathleen
Kathleen 2016년 2월 17일
댓글: Star Strider 2016년 2월 17일
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
  댓글 수: 2
Kathleen
Kathleen 2016년 2월 17일
Very well, thank you!
Star Strider
Star Strider 2016년 2월 17일
My pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (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