Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have a calculation that will give me a lot of ordered pairs. For each such pair in a list, I want to square the elements and add them together. Here is an example of the kind of list I have

{{-3 a, 3 a}, {-1 a,  a}, {-1 a, a}, {-1 a,  a}}

In this instance I would have 18 a^2 for the first pair and so on.

share|improve this question

closed as too localized by Oleksandr R., Michael E2, Verbeia May 21 '13 at 7:49

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

There are several options (and many variants have been asked before here)... the simplest: pairs /. {a_, b_} :> a^2 + b^2 –  rm -rf May 14 '13 at 21:36
you aren't using proper Mathematica syntax. Lists go between { } pairs –  belisarius May 14 '13 at 21:43
Plus @@@ (data^2). Power is Listable. –  Verbeia May 15 '13 at 2:56
add comment

1 Answer 1

data = {{-3 a, 3 a}, {-a, a}, {-a, a}, {-a, a}};

rm-rf's comment:

data /. {a_, b_} :> a^2 + b^2

{18 a^2, 2 a^2, 2 a^2, 2 a^2}

Power is Listable, meaning:


{{9 a^2, 9 a^2}, {a^2, a^2}, {a^2, a^2}, {a^2, a^2}}

Thus, Verbeia's comment:

Plus @@@ (data^2)

{18 a^2, 2 a^2, 2 a^2, 2 a^2}


Total[data^2, {2}]

{18 a^2, 2 a^2, 2 a^2, 2 a^2}

Perhaps for Mathematica newcomers mapping an operator over the list of pairs will seem more intuitive. Let's take this in two steps to make it easy to understand what's going on. First define the operator

operator[{x_, y_}] := x^2 + y^2

Second map it over the data list

Map[operator, data]

{18 a^2, 2 a^2, 2 a^2, 2 a^2}

Of course there is a way to express this in one line which is not so easy to understand.

(#1^2 + #2^2)&[Sequence @@ #]& /@ data

{18 a^2, 2 a^2, 2 a^2, 2 a^2}

share|improve this answer
add comment

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