5
$\begingroup$

I have a particle which is hopping between positions in 3D space

hops = {{1, 1, 1}, {2, 2, 2}, {1, 1, 1}, {2, 2, 2}}

I wish to calculate the the total distance hopped.

Is there a good way to do this?

At the moment I have a for loop storing the total, which adds the differences like this

total = 0;

For[i = 1, i <= 3, i++ ,
  temp = EuclideanDistance[hops[[i]], hops[[i + 1]]];
  total = total + temp ; 
  ];

But, I wonder if I could do this better.

$\endgroup$
6
$\begingroup$
Total[Sqrt[Total[Differences[N@hops]^2, {2}]]]

If performance matter then

Total[Sqrt[Dot[Differences[N@hops]^2,ConstantArray[1., Dimensions[hops][[2]]]]]]

is even a bit faster.

Generally, try to avoid For (Do is a bit better than For) for it is rather a top level construct in Mathematica.

$\endgroup$
5
$\begingroup$

An alternate approach using RegionMeasure

hops = {{1, 1, 1}, {2, 2, 2}, {1, 1, 1}, {2, 2, 2}};

Total[RegionMeasure /@ Line /@ Partition[hops, 2, 1]] // RepeatedTiming

{0.00052, 3 Sqrt[3]}

The timing is much slower than the solution provided by Henrik Schumacher

Total[Sqrt[Total[Differences[N@hops]^2, {2}]]] // RepeatedTiming

(* {0.000016, 5.19615} *)

EDIT: Another variation

Total[EuclideanDistance @@@ Partition[N@hops, 2, 1]] // RepeatedTiming

(* {0.000013, 5.19615} *)
$\endgroup$
4
$\begingroup$

Using BlockMap and EuclideanDistance

Total@BlockMap[EuclideanDistance @@ # &, N@hops, 2, 1] // RepeatedTiming

{0.000061, 5.19615}

A bit slower than Henrik's solution

Total[Sqrt[Total[Differences[N@hops]^2, {2}]]] // RepeatedTiming

{0.0000121, 5.19615}

$\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.