3
$\begingroup$

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

$\endgroup$
  • 1
    $\begingroup$ What are those naked square brackets for? [] used for passing arguments to functions (e.g. Abs), you almost got it: Abs[#1 - a] & /@ a. $\endgroup$ – swish May 10 '17 at 17:02
  • 1
    $\begingroup$ 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). $\endgroup$ – Gregory Klopper May 12 '17 at 16:27
3
$\begingroup$
Total@Outer[Abs[#1 - #2] &, a, a]
$\endgroup$
  • $\begingroup$ I voted this one for this is the simplest!ddd $\endgroup$ – user1470393 May 10 '17 at 18:35
  • $\begingroup$ Thanks. I went through several alternatives but liked it best myself! Outer is extremely powerful. $\endgroup$ – David G. Stork May 10 '17 at 18:36
7
$\begingroup$
Total[DistanceMatrix[a]]

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

$\endgroup$
2
$\begingroup$

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

s=Length@a;Plus@@Table[Abs[a[[i]]-a[[j]]],{j, s},{i, s}]
$\endgroup$
  • $\begingroup$ You didn't complete the task, which is to calculate the total of each sub-array. $\endgroup$ – David G. Stork May 10 '17 at 17:08
  • 2
    $\begingroup$ you are right! I "totally" forgot it $\endgroup$ – J42161217 May 10 '17 at 17:12
2
$\begingroup$

Avoid 1 loop:

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

Avoid both loops:

 Total[Abs[ConstantArray[a, Length[a]] - a]]
$\endgroup$
2
$\begingroup$
(*Method 1*)
Total@Outer[Abs@*Plus, a, -a]

(*Method 2*)
Permutations[a, {2}]. {1, -1} // Plus @@@ Abs@Partition[#, 4] &
$\endgroup$
0
$\begingroup$
Distribute[{{a}, a}, List, List, List, Total@Abs[#1 - #2] &]

{10, 7, 6, 7, 10}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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