Find the index of numerically closest value [duplicate]
Asked Answered
L

1

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.

Lapstrake answered 16/4, 2013 at 20:57 Comment(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.Lapstrake
Thanks for the pointer to the post. It was useful :)Lapstrake
@Lapstrake knnsearch is the obvious answer.Cement
@Parag: knnsearch is available since which MATLAB release?Bemoan
@Bemoan how to check that? I use R2011b and its there.Cement
@Parag knnsearch is in the statistics toolboxStutzman
@Stutzman Yes, I know that but how to check in which version of MATLAB it was introduced?Cement
@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.Stutzman
B
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)))
Bemoan answered 16/4, 2013 at 21:24 Comment(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.Irvine
Why not the shorter [~, idx] = min(abs(A'-B))?Gunther

© 2022 - 2024 — McMap. All rights reserved.