Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the nearest index to a specified index in Matlab

I have two vectors in MATLAB, A and B. B contains some indices (1 to end). I have a random index, R (within the range of the vector indices). I want to write a function (or statement) to choose A[z], where z is the most nearest number (i.e index) to R that is not included in B.

Example:

A = [2 3 6 1 9 7 4 5 8]
B = [3 4 5 6 7 8]
R = 5

The function must return 3, because the most nearest index is 2, because 5-2<9-5 and 2 is not in B, so A[2] = 3;

Thanks

like image 636
remo Avatar asked Nov 05 '12 08:11

remo


2 Answers

Improving jacob's answer, here's the correct solution:

[result, z] = min(abs(R - setxor(B, 1:numel(A))))

And in your case that yields z = 2 and result = A(2) = 3.

like image 106
Eitan T Avatar answered Sep 27 '22 20:09

Eitan T


if I understand correctly, you could do an exclude first, to find the indices not in B, i.e. excl = A(setxor(B,1:length(A))). Then it is easy to get the min like this excl(min(abs(R-excl))).

like image 41
jacob Avatar answered Sep 27 '22 21:09

jacob