Find a numerically close index

Let's say I have 2 matrices in matlab:

A = [1 4 6 9 11 13 15 18 21]

B = [2 10 19]

Is there a function that I can use, so for each element of B I can find the index of the closest value for this element in A. For example, in the above example: 2.10 and 19 are numerically closest to 1.9 and 18 in A, and indices 1, 9 and 18 are 1.4 and 8, so the function should be returned [1 4 8].

I know that I can use loops for this, but Matlab doesn't really like loops, and my matrices are too big, and repeating all the values ​​will be very expensive in time.

+1
source share
1 answer

I would do the following:

% clc,clear all,close all
A = [1 4 6 9 11 13 15 18 21];
B = [2 10 19];
C = abs(bsxfun(@minus,A',B));
[~,idx] = min(C(:,1:size(C,2)))
+4
source

All Articles