How do I compare all elements of two arrays?

前端 未结 3 891
北恋
北恋 2020-11-30 04:05

I have two big arrays with about 1000 rows and 1000 columns. I need to compare each element of these arrays and store 1 in another array if the corresponding elements are eq

3条回答
  •  -上瘾入骨i
    2020-11-30 04:59

    The answers given are all correct. I just wanted to elaborate on gnovice's remark about floating-point testing.

    When comparing floating-point numbers for equality, it is necessary to use a tolerance value. Two types of tolerance comparisons are commonly used: absolute tolerance and relative tolerance. (source)

    An absolute tolerance comparison of a and b looks like:

    |a-b| < tol
    

    A relative tolerance comparison looks like:

    |a-b| < tol*max(|a|,|b|) + tol_floor
    

    You can implement the above two as anonymous functions:

    %# absolute tolerance equality
    isequalAbs = @(x,y,tol) ( abs(x-y) <= tol );
    
    %# relative tolerance equality
    isequalRel = @(x,y,tol) ( abs(x-y) <= ( tol*max(abs(x),abs(y)) + eps) );
    

    Then you can use them as:

    %# let x and y be scalars/vectors/matrices of same size
    x == y
    isequalAbs(x, y, 1e-6)
    isequalRel(x, y, 1e-6)
    

提交回复
热议问题