-1

I have the following multiset X, in which I want to find the distances between all the numbers. Is there any way to integrate this into a FOR LOOP so that If I was given a different sized multiset, I wouldn't have to manually do it like i did below?

the final answer IS [0,2, 2, 3, 3, 4, 5, 6, 7, 8, 10] (sorted) for this example

X=c(0,10,8,3,6)
L=length(X)
print(L)

##for(i in seq(from=1, to=L )){}

print(abs(X[1]-X[2]),  abs(X[1]-X[3]),
    abs(X[1]-X[4]),  abs(X[1]-X[5]),
    abs(X[1]-X[6]),  

    abs(X[2]-X[3]), abs(X[2]-X[4]),
    abs(X[2]-X[5]),  abs(X[2]-X[6]),


    abs(X[3]-X[4]),  abs(X[3]-X[5]),
    abs(X[3]-X[6]),  


    abs(X[4]-X[5]), abs(X[4]-X[6]),


    abs(X[5]-X[6])  

        )
Gabriel
  • 405
  • 1
  • 6
  • 16

1 Answers1

5

You may see this vector as a column vector and apply dist:

sort(dist(X))
# [1]  2  2  3  3  4  5  6  7  8 10
Julius Vainora
  • 47,421
  • 9
  • 90
  • 102