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)
0 个评论
采纳的回答
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
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
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 Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!