Format a matrix with entries displayed as exact values
67 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Dana
on 18 Sep 2020
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 Comments
Dana
on 18 Sep 2020
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
on 19 Sep 2020
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.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!