8
$\begingroup$

I have a list of elements and I would like to create a new list by applying a function to successive overlapping pairs from the original list.

Specifically, I am trying to compute the Pythagorean sum of each pair. So, if the original list is {$a,b,c,d,...$} I want {$\sqrt{a^2+b^2},\sqrt{b^2+c^2},\sqrt{c^2+d^2},...$}

Since this is similar to the built-in Differences function, (which turns the original list into {$b-a,c-b,d-c,...$}), I expected to find a built-in function along the lines of BuiltIn[f,{a,b,c,d,...},options] where f is defined by the user. But alas, my search has been fruitless...

Thanks in advance!

-----------EDIT-----------

Right after posting this, I came up with

Sqrt[#1^2 + #2^2] & @@@ Subsequences[#, {2}] &@{a, b, c, d}

which does the trick. I was going to update that here, but you all already came through with your answers, so I'll try those as well. Thanks!

$\endgroup$
3
  • 2
    $\begingroup$ Norm /@ Partition[yourList, 2, 1]? $\endgroup$
    – MarcoB
    Commented Apr 22, 2020 at 18:11
  • 3
    $\begingroup$ Perhaps something like Sqrt[#1^2 + #2^2] & @@@ Partition[list, 2, 1]? $\endgroup$ Commented Apr 22, 2020 at 18:11
  • 2
    $\begingroup$ Relevant answers here, in particular PartitionMap. $\endgroup$ Commented Apr 22, 2020 at 18:12

3 Answers 3

8
$\begingroup$

You can use BlockMap + Norm

BlockMap[Norm, {a, b, c, d, e}, 2, 1]
{Sqrt[Abs[a]^2 + Abs[b]^2], Sqrt[Abs[b]^2 + Abs[c]^2], 
  Sqrt[Abs[c]^2 + Abs[d]^2], Sqrt[Abs[d]^2 + Abs[e]^2]}
TeXForm @ Simplify[%, Thread[{a, b, c, d, e} >= 0]]

$\left\{\sqrt{a^2+b^2},\sqrt{b^2+c^2},\sqrt{c^2+d^2},\sqrt{d^2+e^2}\right\}$

$\endgroup$
2
  • $\begingroup$ Beautiful. Thanks! $\endgroup$ Commented Apr 22, 2020 at 18:28
  • 1
    $\begingroup$ @AaronEiben, my pleasure. Thank you for the accept. $\endgroup$
    – kglr
    Commented Apr 22, 2020 at 18:35
2
$\begingroup$
list = {a, b, c, d, e};

Using SequenceCases

SequenceCases[list, x :{_, _} :> Norm[x], Overlaps -> True]

enter image description here

$\endgroup$
1
  • $\begingroup$ Also: SequenceCases[list, {a_, b_} :> Sqrt[a^2 + b^2], Overlaps -> True] $\endgroup$
    – Syed
    Commented Feb 17 at 7:24
1
$\begingroup$
l = {a, b, c, d, e};

Using FoldPairList:

f = List /@ FoldPairList[TakeDrop, #, {2, 2}] & /@ {#, RotateLeft@#} &;

Simplify[Norm @@@ Riffle @@ f@l, Thread[l > 0]]

enter image description here

A simpler alternative that uses FoldPairList (Thanks to @Syed!):

FoldPairList[ {Sqrt[#1^2 + #2^2], #2} &, list]

enter image description here

$\endgroup$
1
  • 1
    $\begingroup$ FoldPairList[ {Sqrt[#1^2 + #2^2], #2} &, list] $\endgroup$
    – Syed
    Commented Feb 17 at 7:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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