0

I have several numbers in an array and I would like to find the difference between each one and sort by the lowest result (I don't want to repeat items). I tried using the command "perms" since it gets all the permutations

v = [120;124;130];
p = perms(v)

but it doesn't seem to work the way I would like. Does anyone have any other suggestions

Example: I have 3 numbers a=[120,124,130] (please note there could be hundreds of numbers) and it would find the differences between the numbers, then sort by the result. The calculations would look like the text below.

124-120 =4
130-124 =6
130-120 =10

So the final array b will look like the array below

b=
    [124 120 4
    130 124 6
    130 120 10]

PS: I'm using octave 3.8.1 which is like matlab

Rick T
  • 3,349
  • 10
  • 54
  • 119
  • so you want to find the differences between all pairs of numbers in a vector. Then what exactly do you want to do with the result? store the unique differences sorted? That last part is not clear. What is the expected output here? This sounds similar to PDIST function.. – Amro Mar 26 '16 at 13:22
  • Yes I added what the final array would look like in the question. – Rick T Mar 26 '16 at 13:30

2 Answers2

0

We can use the PDIST function to compute pair-wise distances, then using a combination of ndgrid and tril to get indices into the original values of the vector. Finally we sort using according to distances:

v = [120;124;130];
D = pdist(v, 'cityblock');
[a,b] = ndgrid(1:numel(v), 1:numel(v));
out = sortrows([v(nonzeros(tril(a,-1))) v(nonzeros(tril(b,-1))) D(:)], 3)
Amro
  • 123,847
  • 25
  • 243
  • 454
  • That looks great but what if I don't have access to the pdist function? – Rick T Mar 26 '16 at 13:45
  • the function is in the statistics toolbox (both MATLAB and Octave). Anyway it's not hard to implement, you just compute the distance/difference between every pair of numbers. Just yesterday I posted an answer showing different implementations of PDIST2 (which is quite similar to PDIST, `squareform(pdist2(v,v))` is like `pdist(v)` since PDIST only returns the lower half of the otherwise symmetric matrix): http://stackoverflow.com/a/36225650/97160 – Amro Mar 26 '16 at 13:55
  • Thanks I didn't want to load the whole statistics toolbox – Rick T Mar 26 '16 at 14:10
  • ok, here is the source code of the function anyway: https://sourceforge.net/p/octave/statistics/ci/default/tree/inst/pdist.m – Amro Mar 26 '16 at 14:18
0

For those that can't load the statistics toolbox Thanks goes to @Amro

v = [120;124.6;130];
%taken out from pdist.m from statistics package
order = nchoosek(1:rows(v),2);
Xi = order(:,1);
Yi = order(:,2);
X = v';
d = X(:,Xi) - X(:,Yi);
y = norm (d, "cols");

[a,b] = ndgrid(1:numel(v), 1:numel(v));
out = sortrows([v(nonzeros(tril(a,-1))) v(nonzeros(tril(b,-1))) y(:)], 3)

out=
    124.6000   120.0000     4.6000
       130.0000   124.6000     5.4000
       130.0000   120.0000    10.0000
Rick T
  • 3,349
  • 10
  • 54
  • 119