# avoiding writing loops

I have a list

a={1,2,3,4,5}


I want to calculate absolute differences of each element with all other elements

 b={{0,1,2,3,4},{1,0,1,2,3},{2,1,0,1,2},{3,2,1,0,1},{4,3,2,1,0}}


and then calculate the total for each subarray

  c={10,7,6,7,10}


I want to write it in one line basically, need help here

 b=[#1-a]&/@a  isn't working.


Do someone has an easy way to write it out, instead of using any module loop? thanks in advance

• What are those naked square brackets for? [] used for passing arguments to functions (e.g. Abs), you almost got it: Abs[#1 - a] & /@ a. May 10, 2017 at 17:02
• I hope that you're just running an experiment in trying to learn Mathematica, because what you're trying to do is already implemented as a function: CentralFeature[a]. For graphs it's GraphCenter[g] and for geometric data SpatialMedian[a] (not necessarily a point in your set, though in your example it would have been 3). May 12, 2017 at 16:27

## 6 Answers

Total@Outer[Abs[#1 - #2] &, a, a]

• I voted this one for this is the simplest!ddd May 10, 2017 at 18:35
• Thanks. I went through several alternatives but liked it best myself! Outer is extremely powerful. May 10, 2017 at 18:36
Total[DistanceMatrix[a]]


...too short to be an acceptable answer (minimum is 30 characters) without some meaningless commentary

is this code golf? (cause I lost...)

s=Length@a;Plus@@Table[Abs[a[[i]]-a[[j]]],{j, s},{i, s}]

• You didn't complete the task, which is to calculate the total of each sub-array. May 10, 2017 at 17:08
• you are right! I "totally" forgot it May 10, 2017 at 17:12

Avoid 1 loop:

 Total[Abs[a - # & /@ a]]


Avoid both loops:

 Total[Abs[ConstantArray[a, Length[a]] - a]]

(*Method 1*)
Total@Outer[Abs@*Plus, a, -a]

(*Method 2*)
Permutations[a, {2}]. {1, -1} // Plus @@@ Abs@Partition[#, 4] &

Distribute[{{a}, a}, List, List, List, Total@Abs[#1 - #2] &]


{10, 7, 6, 7, 10}