1

I'm coming to python from Matlab. In Matlab, given two vectors that are not necessarily the same length, they can be added if one is a row vector and one is a column vector.

v1 = [1 3 5 7]

v2 = [2 4 6]'

v1 + v2

ans =

 3     5     7     9
 5     7     9    11
 7     9    11    13

I am trying to produce the same behavior in python given two numpy arrays. Looping first came to mind:

import numpy as np
v1 = np.array([1,3,5,7])
v2 = np.array([2,4,6])
v3 = np.empty((3,4,))
v3[:] = np.nan

for i in range(0,3):
    v3[i,:] = v1 + v2[i]

Is there a more concise and efficient way?

1
  • In your MATLAB size(v1) is (1,4), size(v2) is (3,1). Just make the numpy arrays the same shape. (though the numpy v1 is ok with (4,) shape). Commented Aug 6, 2020 at 15:39

2 Answers 2

1
import numpy as np

v1 = np.array([1, 3, 5, 7])
v2 = np.array([2, 4, 6])

v1 + v2[:, None]

You can read more about numpy's broadcasting rules.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this out:

for i in v2:
  z = []
  for j in v1:
    z.append(i+j)
  
  print(z)

1 Comment

You typically don't want to use for loops with numpy arrays. Vectorized approaches are often faster and cleaner.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.