Find the index of numerically closest value [duplicate]

寵の児 提交于 2019-12-23 04:14:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!