Format a matrix with entries displayed as exact values

67 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by