Format a matrix with entries displayed as exact values

74 ビュー (過去 30 日間)
Aleem Andrew
Aleem Andrew 2020 年 9 月 18 日
コメント済み: madhan ravi 2020 年 9 月 19 日
I am trying to print a matrix with its entries displayed as exact values not fractional approximations. For example, the following code should print A exactly as it is initialized (not approximate sqrt(2) as 1393/985) but displays fractions. What format specification instead of rat should be used?
format rat
AB = [0 1 1; sqrt(2) 2 0; 0 1 1];
disp("AB: "); disp(AB)

採用された回答

Dana
Dana 2020 年 9 月 18 日
I'm not sure exactly what you're after. Here are some possibilities
>> format short
>> disp(AB)
0 1.0000 1.0000
1.4142 2.0000 0
0 1.0000 1.0000
>> format long
>> disp(AB)
0 1.000000000000000 1.000000000000000
1.414213562373095 2.000000000000000 0
0 1.000000000000000 1.000000000000000
>> format shortg
>> disp(AB)
0 1 1
1.4142 2 0
0 1 1
>> format longg
>> disp(AB)
0 1 1
1.4142135623731 2 0
0 1 1
If you're saying you want it to literally say "sqrt(2)", then you can't do that using numeric arrays. As soon as you set an element of a numeric array equal to sqrt(2), MATLAB forgets how it arrived at that value, and only remembers the floating-point approximation. The only option I can see would be to use the Symbolic Toolbox:
>> AB = sym([0 1 1; sqrt(sym(2)) 2 0; 0 1 1]);
>> disp("AB: "); disp(AB)
AB:
[ 0, 1, 1]
[ 2^(1/2), 2, 0]
[ 0, 1, 1]
You can then convert this to a numeric array any time using eval:
>> eval(AB)
ans =
0 1 1
1.4142 2 0
0 1 1
  4 件のコメント
Dana
Dana 2020 年 9 月 18 日
Not sure what the relevance of that is here madhan? This use of eval isn't about variable naming, it's about converting a symbolic array to a numeric one.
madhan ravi
madhan ravi 2020 年 9 月 19 日
a simple use of double() would do the trick. Generally eval() is not recommended, if you read that link entirely, it’ll tell you the reasons why not to use that function.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeNumbers and Precision についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by