找到数值最接近的索引 [英] Find the index of numerically closest value
问题描述
A = [1 4 6 9 11 13 15 18 21]
B = [2 10 19]
是否有我可以使用的函数对于B中的每一个元素,我都可以找到A中最接近这个元素的索引。例如,在上面的例子中:2,10和19在数值上最接近于A中的1,9和18,而1,9和18的索引是1,4和8,所以函数应该返回[1 4 8]。
我知道我可以使用循环来做到这一点,但matlab并不真的喜欢循环加我的矩阵太大,迭代所有的值将是非常昂贵的时间。
我会按以下步骤操作:
%clc,全部清除,全部关闭
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)))
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.
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)))
这篇关于找到数值最接近的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!