MATLAB: Find the closest element in each row of an array to each element of a vector

arrayelementsubtractvector

Hi,
I am looking to find the closest element (an its index) in each row of an array to each element of a vector. which means I would have a vector for each element of a vector. something like this:
a = [1 2 3];
b = [2 1 3;
5 2 3;
4 5 1];
and I want to have
ans = [1 2 1 %for the first element of vector or 1 (closest elements of
% each row of array to the first element of the vector)
2 2 1 %for the second element of vector or 2
3 3 4] %for the third element of vector or 3
for two vectors I can use this, e.g.:
b = [2 3 4 5]
[err,err_ind] = min(abs(bsxfun(@minus,a,b')));
but I have no idea how can I do the same when b is an array (without using loop).

Best Answer

a = [1 2 3];
b = [2 1 3;
5 2 3;
4 5 1];
[~,err_ind] = min(abs(bsxfun(@minus,reshape(a,1,1,[]),b)),[],2);
out = squeeze(err_ind);