Elements of a vector whose difference is minimum?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Marco Bakker
am 6 Okt. 2016
Bearbeitet: Matt J
am 6 Okt. 2016
Is it possible to find the elements of a vector whose difference is minimum?
0 Kommentare
Akzeptierte Antwort
Matt J
am 6 Okt. 2016
Bearbeitet: Matt J
am 6 Okt. 2016
If v is the given vector,
N=length(v);
G=abs(bsxfun(@minus,v(:),v(:).'));
G(1:N+1:end)=nan;
[i,j]=find(G==min(G(:)));
v(i), v(j)
1 Kommentar
LauraLee Austin
am 6 Okt. 2016
Matt J, I like your approach, but it's missing a step which removes the difference of itself (i.e. element 2 minus element 2 equals 0)
G=abs(bsxfun(@minus,v(:),v(:).'));
a = 1:1+length(v):numel(G);
G(a) = NaN;
[i,j]=find(G==min(G(:)));
Weitere Antworten (1)
Matt J
am 6 Okt. 2016
Bearbeitet: Matt J
am 6 Okt. 2016
If v is the given vector,
N=length(v);
idx=nchoosek(1:N,2);
I=idx(:,1); J=idx(:,2);
D = abs( v(I) - v(J) );
imin = D==min(D);
v(I(imin)) , v( J(imin) )
Note that I, J can be re-used for further input vectors, v, that are the same length, N.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Tables finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!