erbal
erbal

Reputation: 431

How to find two closest (nearest) values within a vector in MATLAB?

I have a vector e.g. A=[2.29 2.56 2.67 2.44 2.52 1.23]

I am interested to find two closest (almost equal) values with in this vector.

Upvotes: 0

Views: 1386

Answers (2)

ibezito
ibezito

Reputation: 5822

One-Liner Solution

res = A(repmat(find(abs(diff(A))==min(abs(diff(A)))),2,1)+[0;1]);

More descriptive solution

%finds the index with the minimal difference in A
minDiffInd = find(abs(diff(A))==min(abs(diff(A))));
%extract this index, and it's neighbor index from A
val1 = A(minDiffInd);
val2 = A(minDiffInd+1);

Result:

val1 = 2.4400
val2 = 2.5200

Upvotes: 2

kpie
kpie

Reputation: 11100

You can use pdist().

as in pdist(A,A)

Upvotes: 0

Related Questions