1

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.

Stuart M
  • 11,458
  • 6
  • 45
  • 59
vsx06
  • 87
  • 3
  • 8
  • Currently, I reduce the time cost by sorting the two matrices and then looking for values in a way so that the index of last closest found value in A is saved and then the search for the closest value for next element in B starts at this saved value instead of 1. everytime. – vsx06 Apr 16 '13 at 21:04
  • Thanks for the pointer to the post. It was useful :) – vsx06 Apr 16 '13 at 21:11
  • @vsx06 `knnsearch` is the obvious answer. – Autonomous Apr 16 '13 at 21:27
  • @Parag: `knnsearch` is available since which MATLAB release? – fpe Apr 16 '13 at 21:38
  • @fpe how to check that? I use R2011b and its there. – Autonomous Apr 16 '13 at 22:57
  • @Parag `knnsearch` is in the statistics toolbox – Dan Apr 17 '13 at 06:25
  • @Dan Yes, I know that but how to check in which version of MATLAB it was introduced? – Autonomous Apr 17 '13 at 06:26
  • @Parag I don't know but my point is that the fact that it's in the toolbox explains why fpe or others might not have access to it. – Dan Apr 17 '13 at 06:29

1 Answers1

4

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)))
fpe
  • 2,700
  • 2
  • 23
  • 47
  • 2
    Please do not add `clc,clear all,close all`. I might want to retain in cache all the executed functions for performance and keep my figures open. – Oleg Apr 16 '13 at 21:30
  • Why not the shorter `[~, idx] = min(abs(A'-B))`? – tstenner Mar 26 '19 at 15:44