How do I find the indices of a given array A1, *any* of whose values are practically equivalent to *any* of the values of a second array A2?

前端 未结 2 1572
挽巷
挽巷 2020-12-11 08:04

By \"practically equivalent\", I mean that their distances are of order epsilon apart (or 0.000001). Equality in MATLAB often doesn\'t really work for long floating numbers.

2条回答
  •  情深已故
    2020-12-11 08:28

    Since you care about a distance from any element to any element, you can create a distance matrix from the vectorized matrices and probe that for the distance threshold. Example:

    A = rand(10, 4); % (example) matrix A 
    B = rand(3, 5);  % matrix B of different size 
    minDist = 0.005; 
    

    Solution: Repeat vectorized matrices, column- and row-wise to get same size matrices and apply matrix-based distance estimation:

    Da = repmat(A(:), 1, length(B(:)));  % size 40 x 15
    Db = repmat(B(:)', length(A(:)), 1); % size 40 x 15 
    DD = Da - Db; 
    indA = any(abs(DD) < minDist, 2); 
    

    The use of any() will give you logical indices to any value of A that is close to any value of B). You can directly index/return the elements of A using indA.

    The matrix DD (as @Shai also points out) can be equivalently estimated through bsxfun

    DD = bsxfun(@minus, A(:), B(:)');
    

    In addition: you can map from row-index (corresponding to A elements) back to matrix A indices using:

    [iA, jA] = ind2sub(size(A), indA);
    

    Assert/test that all the returned values are less than minDist,e.g. using:

    for k = 1:length(iA); 
        d(k) = min(min(abs(A(iA(k), jA(k)) - B)));
    end
    all(d < minDist)
    

    (tested in Octave 3.6.2)

提交回复
热议问题