0
$\begingroup$

I want to get the difference of all elements of a list for example:

$L=\{1,2,3,4,5,6\}$ for any $i$ and $j$ $\in L$ return the differences, for example for the first element $1$ we get the difference with the rest of elements $\{2,3,4,5,6\}$ we can use the Abs to get the absolute value of the differnce.

I used Differences but this gives the successive differences of elements in list.

Thank you.

$\endgroup$
0

1 Answer 1

6
$\begingroup$
L = Range[6]
Outer[#1-#2&, L, L]
$\endgroup$
5
  • 4
    $\begingroup$ Maybe easier to read: Outer[Subtract,L,L] $\endgroup$
    – Jens
    Jun 29, 2016 at 18:20
  • 3
    $\begingroup$ DistanceMatrix[] is better for this. $\endgroup$ Jun 29, 2016 at 19:52
  • 1
    $\begingroup$ @J.M. correct and more concise certainly. But better? I'd prefer a design pattern that I can reuse in any number of ways over a relatively obscure function that is only in the latest versions of Mathematica. $\endgroup$
    – mikado
    Jun 29, 2016 at 19:57
  • 2
    $\begingroup$ @mikado. Depends on what you want. If DistanceMatrix[] is optimized for this particular calculation, then it's worth using for large lists in certain applications. There's a difference between solving a particular problem and learning general coding practice, and some people don't need the latter. $\endgroup$
    – march
    Jun 29, 2016 at 20:08
  • $\begingroup$ @J.M. I hadn't thought of DistanceMatrix - I guess it's too new (only introduced last year)... now that I looked for it it seems that this is a duplicate. $\endgroup$
    – Jens
    Jun 29, 2016 at 21:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.