TransWikia.com

Add a vector to a list of vectors

Mathematica Asked on June 10, 2021

What is the syntax to add a vector v1 to each vector in a list of vectors 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}}

7 Answers

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

Correct answer by Artes on June 10, 2021

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

(v1 + # &) /@ v2

which is a short form of:

Map[ v1 + # &, v2 ]

Answered by user8074 on June 10, 2021

Alternative method using the magic that is Inner:

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

Answered by Patrick Stevens on June 10, 2021

Also:

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

Answered by SquareOne on June 10, 2021

I couldn't resist adding this:

TranslationTransform[v1] /@ v2

Answered by J. M.'s ennui on June 10, 2021

Total[Tuples[{{v1}, v2}], {2}]
 {{a + d, b + e, c + f}, {a + g, b + h, c + i}, {a + j, b + k, c + l}}
Distribute[{{v1}, v2}, List, List, List, Plus]
 {{a + d, b + e, c + f}, {a + g, b + h, c + i}, {a + j, b + k, c + l}}

Answered by kglr on June 10, 2021

Using Outer is also an efficient approach, in some cases faster than using Transpose twice

v1 = RandomReal[1, 10^5];
v2 = RandomReal[1, {10^3, 10^5}];

r1 = Transpose[v1 + Transpose[v2]]; // RepeatedTiming
r2 = Outer[Plus, {v1}, v2, 1][[1]]; // RepeatedTiming
r1 === r2

Output

{0.619, Null}
{0.42, Null}
True

Related link: Improving Map Function on Lists

Answered by chyanog on June 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP