I'm attempting to align certain text in a text file that I'm writing with matlab. Right now part of my code looks like this:
'%6.4f\tTwFAM1Sh(2) - Mode 1, coefficient of x^2 term\r\n' ...
'%6.4f\tTwFAM1Sh(3) - , coefficient of x^3 term\r\n' ... ''%6.4f\tTwFAM1Sh(4) - , coefficient of x^4 term\r\n' ...
'%6.4f\tTwFAM1Sh(5) - , coefficient of x^5 term\r\n' ...
and it prints this:
1.4401 TwFAM1Sh(2) - Mode 1, coefficient of x^2 term
-0.4228 TwFAM1Sh(3) - , coefficient of x^3 term
-0.0239 TwFAM1Sh(4) - , coefficient of x^4 term
0.0027 TwFAM1Sh(5) - , coefficient of x^5 term
but what I need it to do is this:
0.8164 TwFAM1Sh(2) - Mode 1, coefficient of x^2 term
0.3370 TwFAM1Sh(3) - , coefficient of x^3 term
-0.3668 TwFAM1Sh(4) - , coefficient of x^4 term
0.4695 TwFAM1Sh(5) - , coefficient of x^5 term
...The second part prints the numbers aligned from the last integer rather than aligning the first integer. Any guesses??

 採用された回答

Cedric
Cedric 2013 年 7 月 25 日
編集済み: Cedric 2013 年 7 月 25 日

5 投票

Right justification is the default and you would have to use '-' to enforce left justification. The issue with your code is that with the precision of 4 that you set up, negative numbers lead to a field width larger than 6. For what you are trying to achieve, what about increasing the field width? Illustration:
>> fprintf('%7.4f\n', [pi, -pi]) ;
3.1416
-3.1416
>> fprintf('%-7.4f\n', [pi, -pi]) ;
3.1416
-3.1416
or decreasing the precision..
>> fprintf('%6.3f\n', [pi, -pi]) ;
3.142
-3.142

3 件のコメント

Zach Pacheco
Zach Pacheco 2013 年 7 月 25 日
That makes sense, but I don't know if that second or third number will always be negative. The code I'm using can produce negative or positive values. That's why I'm trying to get a right hand alignment
Cedric
Cedric 2013 年 7 月 25 日
What I am showing with +/-pi is that it works for both when the field width is large enough for the negative sign, precisely because there is this right alignment by default.
Zach Pacheco
Zach Pacheco 2013 年 7 月 25 日
Increasing the field width worked!! Thank you very much

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Entering Commands についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by