필터 지우기
필터 지우기

equality operator between matrix and scalar

조회 수: 1 (최근 30일)
A
A 2012년 4월 17일
consider:
a=[-1:0.1:1];
c=a==.1;
it returns c as a matrix of nulls; while I expect c(12) to be 1.

채택된 답변

Matt Kindig
Matt Kindig 2012년 4월 17일
This is due to floating point precision errors, explained here: http://blogs.mathworks.com/loren/2006/08/23/a-glimpse-into-floating-point-accuracy/
A better way to do this is by comparing against a tolerance, such as:
c = abs(a-0.1)<=eps

추가 답변 (3개)

Kye Taylor
Kye Taylor 2012년 4월 17일
The value .1 and a(12) differ by only one bit as a result of numerical round-off. You can see this with the commands
num2hex(.1)
num2hex(a(12))
A better way to test equality takes into account the possibility of numerical round-off. For example, create your new c variable with the command
c = abs(a-0.1)<=eps(max(a));

Walter Roberson
Walter Roberson 2012년 4월 17일

James Tursa
James Tursa 2012년 4월 17일
You can try this to see what the numbers are exactly:
num2strexact((-1:0.1:1)')
Sometimes a beter way to do this is to have an array with integer values to start with and then create a 2nd array with the fractional values. E.g.,
A = -10:10;
a = A / 10;
c = A==1;
You can use a for downstream calculations just like before, and you can use c for the value testing.
You can find num2strexact on the FEX here:

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by