필터 지우기
필터 지우기

vectors equality test failure - decimals and sign issue on zeros

조회 수: 1 (최근 30일)
VMat
VMat 2016년 8월 13일
편집: Stephen23 2016년 8월 14일
I shall test two vectors of same dimension for their equality: namely, x0 and xhat as defined below (they belong to different functions, xhat is return value of inner called function).
--- x0 ---
support = randsample(n,k);
x0 = zeros(n,1);
x0(support) = randn(k,1);
--- xhat ---
b = A*x0;
cvx_quiet(true);
cvx_begin
variable x(n)
minimize( norm(x,1) )
subject to
A*x == b
cvx_end
xhat = x;
To test equality I use:
if isequal(xhat, x0, 1e-6)
or
if isequal(xhat, x0)
condition which never verifies because x0 contains '0' or other (4 decimals, signed), while xhat contains '0.0000', '-0.0000', or other (4 decimals, signed). The algorithm works properly as values (real) in magnitude are the same in both vectors, and at the same indexes, therefore the condition for 'equality' is satisfied in facts, but I miss the way to code it in matlab.
How can I 'turn' xhat into x0, so to get isequal() function answering TRUE ?
Many thanks!
  댓글 수: 2
VMat
VMat 2016년 8월 14일
Thank you very much Geoff: problem solved.
Stephen23
Stephen23 2016년 8월 14일
편집: Stephen23 2016년 8월 14일
According to the isequal documentation, this syntax
isequal(xhat, x0, 1e-6)
simply tests that all three arrays are equal, i.e. that xhat is the same as x0, and x0 is the same as 1e-6. Is that what you want to test for? Did you read the documentation ?

댓글을 달려면 로그인하십시오.

답변 (1개)

Geoff Hayes
Geoff Hayes 2016년 8월 13일
VMat - see http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F for some details on comparing two floating-point numbers. When doing so, you shouldn't be using equality. Instead, compare the absolute difference to a tolerance. For example,
tol = 1.0e-6;
areEqual = all(abs(xhat-x0) < tol);
will return true if the pairwise absolute difference between each element of the two arrays is less than the tolerance.
  댓글 수: 1
Guillaume
Guillaume 2016년 8월 14일
@Vmat,
I guess that this tolerance comparison is what you were trying to do with your isequal(xhat, x0, 1e-6) but that is not how isequal works at all. There is no tolerance argument for isequal. As per the doc, the above simply checks that both xhat and x0 are equal to 1e-6.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Hypothesis Tests에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by