Noor
Noor

Reputation: 125

How to map vector into nearest point in another vector in Matlab?

Assume I have a vector a of length N and another vector b = [-3 -1 1 3], is there any efficient way to map each element of a to its nearest (Euclidean distance) element in b. I do not want to use loops.

Upvotes: 1

Views: 161

Answers (1)

Suever
Suever

Reputation: 65430

You can use bsxfun to compute the difference between every element in the two vectors. This will return a numel(a) x numel(b) matrix of differences. We can then take the absolute value and find the column at which the smallest differences occurs for each element in a (using the second output of min). If you want the actual value of b that is closest to each element in a, you can then use the second output of min to index into b.

a = linspace(-3, 3, 8);
b = [-3 -1 1 3];

[~, closest] = min(abs(bsxfun(@minus, a(:), b(:).')), [], 2);
%     1     1     2     2     3     3     4     4

b_for_each_a = b(closest);
%    -3    -3    -1    -1     1     1     3     3

Your example is in one-dimension so Euclidean distance doesn't actually matter apart from using the absolute value of the distance.

Upvotes: 2

Related Questions