# 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. – swish May 10 '17 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). – Gregory Klopper May 12 '17 at 16:27

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

• I voted this one for this is the simplest!ddd – user1470393 May 10 '17 at 18:35
• Thanks. I went through several alternatives but liked it best myself! Outer is extremely powerful. – David G. Stork May 10 '17 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. – David G. Stork May 10 '17 at 17:08
• you are right! I "totally" forgot it – J42161217 May 10 '17 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}