0

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.

Sardar Usama
  • 19,536
  • 9
  • 36
  • 58
erbal
  • 421
  • 5
  • 18
  • 1
    For clarification, are you interested in the two closest adjacent values or the two closest regardless of position? – RTL Jun 12 '16 at 08:39
  • @RTL: any two closest value, irrespective of position. – erbal Jun 12 '16 at 09:48

2 Answers2

2

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
ibezito
  • 5,782
  • 2
  • 22
  • 46
  • your solution is perfect. Can it be extended to find closest element in any number of (two or more) equal sized vectors? i.e. out of a group of equal sized vectors, how to identify two closest elements in any two vectors, not within a vector as was done in above solution given by you. – erbal Jun 12 '16 at 10:06
  • Posted http://stackoverflow.com/questions/37773140/how-to-find-closest-nearest-value-within-a-vector-to-another-vector-in-matlab it as a separate question. – erbal Jun 12 '16 at 10:31
0

You can use pdist().

as in pdist(A,A)

kpie
  • 9,588
  • 5
  • 28
  • 50