how to use a simple statement to describe a repeat format output about the function "fprintf"?

For example, fprintf(fid,'%4.2f %4.2f %4.2f %4.2f %4.2f',data) there are 5 '%4.2f', Can a simple statement like the (5'%4.2') to simplify the output format? I have no idea about it and do not find in the documents of matlab.

 採用された回答

Matt Fig
Matt Fig 2012 年 11 月 17 日
fprintf(fid,repmat('%4.2f',1,5),data)

3 件のコメント

Liang He
Liang He 2012 年 11 月 22 日
This is a good method,but it can not solve the problem when the format is complex. For example, when the data is 28*10000.I should save the data in the next format fprintf(fid,'%5.2 %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f\n') In the format,there are 8 repeat %4.2 ,but other are different.So,I am wondering are there a method to simplify the repeat part.
Matt Fig
Matt Fig 2012 年 11 月 22 日
編集済み: Matt Fig 2012 年 11 月 22 日
C = {'%5.2f ';'%4.3f ';'\n'};
[C{[1 2*ones(1,8) 3]}]
You can build C with as many elements as needed then pass in an index to get the order and number you need.
Henry Wolkowicz
Henry Wolkowicz 2025 年 4 月 19 日
編集済み: Henry Wolkowicz 2025 年 4 月 19 日
can one complicate things with
C={'%5.2f & '} for latex table purposes? I keep getting 'number' echos if I try this

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2012 年 11 月 17 日
No need to replicate the format string - it will do that automatically. Try it this way:
fprintf(fid,'%4.2f ', data);

3 件のコメント

Liang He
Liang He 2012 年 11 月 22 日
This is a good method,but it can not solve the problem when the format is complex. For example, when the data is 28*10000.I should save the data in the next format fprintf(fid,'%5.2 %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f\n') In the format,there are 8 repeat %4.2 ,but other are different.So,I am wondering are there a method to simplify the repeat part.
Image Analyst
Image Analyst 2012 年 11 月 22 日
Not sure I understand. That will have every 9th element print with a field width of 5 and the 8 numbers in between print with a field width of 4. Also the printout line will have 9 numbers per row whereas your array has 8 numbers per row. Is that what you want, or not? Because that's what you'd be telling it to do.
Liang He
Liang He 2012 年 11 月 22 日
Thank you for your answer, the Matt Fig has solved it.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

タグ

質問済み:

2012 年 11 月 17 日

編集済み:

2025 年 4 月 19 日

Community Treasure Hunt

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

Start Hunting!

Translated by