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

By "practically equivalent," I mean that their distances are in order from each other (or 0.000001). Equality in MATLAB often does not work for long floating numbers.

If I just do abs (A1 - A2) 0.000001, it will not work, since size (A1)! = Size (A2)

+4
source share
2 answers

You can get the answer by calculating the distance between two vectors using the MATLAB pdist2 function.

 dist=pdist2(A1,A2); minDist=min(dist,[],2); indices_A1=minDist<=0.000001; desired_A1=A1(indices_A1); 

Not tested, but should work.

+5
source

Since you care about the distance from any element to any element, you can create a matrix of distances from vectorized matrices and measure it for a distance threshold. Example:

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

Solution . Repeat vectorized matrices, columns and rows to get matrices of the same size and apply a distance estimate based on the matrix:

 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); 

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

The DD matrix (as @Shai also points out) can be equivalently evaluated via bsxfun

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

In addition : you can map from the index of the row (corresponding to the elements of A) back to the matrix A with:

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

Assert / test that all returned values ​​are less than minDist , for example. 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)

+1
source

All Articles