I have two matrices
A = np.array(
B = np.array(
I would like to have a matrix, which is 3x3x2 which is [[A + first row of B], [A + second row of B]]
C = np.array(
I'm aware that I could do np.concatenate((A + B, A + B)), but I won't know how many rows B contains beforehand and for my own programming experience I'm curious if there is a cleaner way to do this.
Best How To :
A = and
B = commands don't generate matrices, but lists of lists. The difference matters because they don't have numpy's nice vector math attached.
Anyway, you could expand
A by creating a new axis using
[:,None], do the addition, and then swap the axes to get the shape you want:
>>> A = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> B = np.array([[1,1,1], [2,2,2]])
>>> (A[:, None] + B).swapaxes(0,1)
array([[[ 2, 3, 4],
[ 5, 6, 7],
[ 8, 9, 10]],
[[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]]])
Note that this has shape (2,3,3), not (3,3,2), but that's the shape your C had, so I went with that.