When using fprintf to format multiple strings, what does the integer after the % sign do?

49 ビュー (過去 30 日間)
Matthew Cooper
Matthew Cooper 2013 年 1 月 29 日
Hi,
Given something such as:
fprintf('%5d %10.3f %8.5e\n',100,2*pi,pi);
What do the numbers directly after the % sign do? I understand that %5d displays an integer, 5 spaces in from the beginning of the line. But, I don't understand what the %10 does. I know the .3f says to display decimal format with 3 decimal places, but what does the 10 do? And what does the %8 do? If I type
fprintf('%5d %3.3f %8.5e\n',100,2*pi,pi); or fprintf('%5d %4.3f %8.5e\n',100,2*pi,pi);
I get the same answer. It isn't until I get to
fprintf('%5d %6.3f %8.5e\n',100,2*pi,pi);
That the spacing changes, and then the spacing increases by 1. So, I see that it seems to be related to the previous spacing argument, but I can't figure out the exact pattern. Clarification would be greatly appreciated. Thank you!

回答 (1 件)

Shashank Prasanna
Shashank Prasanna 2013 年 1 月 29 日
It is the field width or the minimum numbers of characters to print.
Check this link out:
scroll down for a diagrammatic representation and explanation.
  2 件のコメント
Matthew Cooper
Matthew Cooper 2013 年 1 月 30 日
編集済み: Matthew Cooper 2013 年 1 月 30 日
Thank you for the link, but I don't think it's as simple as saying that it is the field width or the minimum numbers of characters to print. If you notice in the example I provided, the second argument seems to depend on the first argument, e.g. %10.2f, %5.3d will produce the same thing as %10.2f, %6.3d and also the same as %10.2f, %7.3d...it doesn't change the spacing until I get to %10.2f, %11.3d. It's as if the second argument has to be greater than the first.
Jan
Jan 2013 年 1 月 30 日
As the documentation explains accurately, the value before the dot is the "field width", and the value after the point the "precision". If a number has more digits, caused by its value and the precision, than allowed by the field width, more digits are written. This means, the first value is a "minimal field width" and spaces are used for padding on demand.

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by