I have two equal sized vectors, e.g.
A=[2.29 2.56 2.77 2.90 2.05] and
B=[2.34 2.62 2.67 2.44 2.52].
I am interested to find closest values (almost equal) in two same size vectors A & B, i.e. out of all elements in A, which value is closest to any element of B? The solution should be extendable to any number of (equal size) vectors also. Means able to find closest values with a group of same sized vectors A,B &C. The two resulting values can be from either of two vectors.
For clarity, i am not interested to find closest values within a single vector. The answer from above example is values 2.56 and 2.52.
Just as a long comment, if you have access to Statistics and Machine Learning Toolbox, then you could use K-Nearest Neighbors functions which have some pros like:
Handling arrays with different length for example when size(A) = [M, 1] and size(B) = [N, 1]
Handling Two dimensional arrays, for example when size(A) = [M, d] and size(B) = [N, d]
Handling different distance types, for example: Euclidean, City block, Chebychev and so many others and even you own custom distances.
Using KDTree Algorithm for some special case which causes a great performance.
Although in your case answer from "Luis Mendo" seems pretty nice, but it is not extendable as what K-Nearest Neighbors functions from toolbox offer.
Update: A sample Code
As a starting point for two vectors using
bsxfun
:now you can put it into a loop etc.
By the way:
would be equivalent to the more obvious:
but I'd rather go for the first solution avoiding the overhead.
And finally the fully vectorized approach for multiple vectors:
This works for a generic number of vectors of possibly different lengths: