What is the syntax to add v1 to each vector in v2? I know it has to be simple, but I really have searched and not found it.

v1 = {a, b, c}
v2 = {{d, e, f}, {g, h, i}, {j, k, l}}

i.e., sum them in a way to give:

{{a + d, b + e,c + f}, {a + g, b + h, c + i}, {a + j, b + k, c + l}}

I recommend using Transpose twice since it is more efficient than other approaches. Moreover Plus has the Listable attribute, thus one need not map Plus over a list (vector).

Transpose[v1 + Transpose[v2]]
{{a + d, b + e, c + f}, {a + g, b + h, c + i}, {a + j, b + k, c + l}}

Having said that remember that one can rewrite it very concisely in the Front-End: Esc tr Esc :

enter image description here

  • $\begingroup$ Hah, clearly my knowledge of Inner isn't well enough entrenched yet. I failed to notice that my Inner effectively simplified to Transpose @* Plus! $\endgroup$ – Patrick Stevens Sep 19 '15 at 22:28
  • $\begingroup$ @ciao Thanks, unfortunately someone unupvoted my answer (it was edited) so I guess it is inadvisable to improve posts. $\endgroup$ – Artes Sep 20 '15 at 0:23
  • 2
    $\begingroup$ @Artes Of course it is advisable to improve posts! $\endgroup$ – Dr. belisarius Sep 20 '15 at 18:24
  • $\begingroup$ In similar contexts ... While I use Transpose all the time - for intuitive clarity and readability, sometimes one can get faster performance using Part and All in its place ... just FYI testData = Table[{{i, 2 i}, 3 i}, {i, 1000000}]; Print@Timing[ Length[ Last[ Transpose[testData]]]]; Print@Timing[ Length[ Part[ testData, All, 2]]]; Print@Timing[ Length[ testData[[ All, 2]]]]; $\endgroup$ – Mark Samuel Tuttle Sep 23 '15 at 13:32

To achieve what you need requires to distribute the sum over v2:

(v1 + # &) /@ v2

which is a short form of:

Map[ v1 + # &, v2 ]
  • $\begingroup$ This is a good one for my list of "expressions that help me understand mathematica syntax"! Thanks. $\endgroup$ – DrBubbles Sep 19 '15 at 22:17

Alternative method using the magic that is Inner:

Inner[Plus, {a, b, c}, Transpose@{{d, e, f}, {g, h, i}, {j, k, l}}, List]


Plus @@@ Thread[{v1, v2}, List, {2}]

I couldn't resist adding this:

TranslationTransform[v1] /@ v2
  • 3
    $\begingroup$ More terse and universal version: TranslationTransform[v1][v2]. $\endgroup$ – Alexey Popkov Oct 12 '15 at 13:39
  • $\begingroup$ This function is for that purpose by far the slowest solution ... $\endgroup$ – mrz May 27 '16 at 21:10

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.