user14554732
user14554732

Reputation:

How to add a array to a column of a matrix? (python numpy)

Like this:

import numpy as np
a = np.zeros((3,3))
b = np.ones((3,1))
a[:,2] += b

expected:

a = 
0,0,1
0,0,1
0,0,1

in fact:

ValueError: non-broadcastable output operand with shape (3,) doesn't match the broadcast shape (3,3)

What should I do?

Upvotes: 0

Views: 173

Answers (1)

JayPeerachai
JayPeerachai

Reputation: 3842

Specifying the range of column is required

e.g. a[:,0:1] for column 0, a[:,1:2] for column 1, and a[:,2:] for column 2.

import numpy as np
a = np.zeros((3,3))
b = np.ones((3,1))
a[:,2:] += b

output:

array([[0., 0., 1.],
       [0., 0., 1.],
       [0., 0., 1.]])

Upvotes: 1

Related Questions