问题
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 I can use so that, for every element in B, I am able to find the index of the closest value to that element in A. For instance, in the above example: 2,10 and 19 are numerically closest to 1,9 and 18 in A, and the indices of 1, 9 and 18 are 1,4 and 8, so the function should return [1 4 8].
I know I can use loops to do this but matlab doesn't really like loops plus my matrices are too big and iterating through all values would be very expensive on time.
回答1:
I would proceed as follows:
% 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)))
来源:https://stackoverflow.com/questions/16046933/find-the-index-of-numerically-closest-value