Need help with fprintf

I am using fprintf to print a table of dates, opponents, scores, and attendance. The problem is the output is not aligned considering the opponents have varying lengths so it throws off everything else. Is there a away to align each column when printing row by row? Both the dates and the opponents are strings and are left aligned but the score column consists of two float values with a dash in between and the attendances is also a float value.
what it gives me:
date opponent score attendance
12/14/17 at Missouri 51-59 1759
1/8/2018 LSU 76-54 2432
2/11/2018 Vanderbilt 62-48 1721
what i want:
date opponent score attendance
12/14/17 at Missouri 51-59 1759
1/8/17 LSU 76-54 2432
2/11/2018 Vanderbilt 62-48 1721

回答 (2 件)

Walter Roberson
Walter Roberson 2018 年 4 月 14 日

0 投票

No. That would require that somehow MATLAB went back and changed output that was already on the screen.
What you need to do instead is figure out the maximum width each column will occupy and format each item in that column to take that width. You can do that with numbers between the '%' and the format letter in the format. For example, %7d to use 7 right-aligned digits for a decimal number. %10.4f for 10 total places including the '.' and 4 decimal places after that (so, 5 before, one decimal point, 4 after = 5+1+4 = 10) for fixed point. %10s for 10-character strings. %-10s if you want the 10 characters to be left-aligned.
Jeff Miller
Jeff Miller 2018 年 4 月 14 日

0 投票

Yes. The basic idea is to use "blanks" to pad out the length of the opponent field on each line to some maximum width that will hold all the different opponents.

カテゴリ

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

タグ

質問済み:

2018 年 4 月 13 日

コメント済み:

2018 年 4 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by