remo
remo

Reputation: 898

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

Upvotes: 7

Views: 276

Answers (3)

remo
remo

Reputation: 898

Please note that setdiff and setxor functions sort the result.

tmpSet = R - setdiff(1:numel(A),B);
[~,z] = min(abs(tmpSet));
z = tmpSet(z);
Result = A(R-z);

The same Example in the question:

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

tmpSet = 5 - {1 2 9} = {4 3 -4}
z = 2
z = 3
Result = A(5-3) = A(2) = 3 

Thank you for your ideas.

Upvotes: 0

Eitan T
Eitan T

Reputation: 32920

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.

Upvotes: 6

jacob
jacob

Reputation: 899

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))).

Upvotes: 2

Related Questions