Format a matrix with entries displayed as exact values
조회 수: 66 (최근 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!