R
The problem is, b it is a "vector column" (i.e., its dimensions are (4, 1) because it has 4 rows and 1 element in each), but the slice in which you try to put it through a[:,1] expects a normal vector (size 4, that is, 1 row with 4 elements or what is the same, form (1,4)).That's precisely what mistake means. "could not broadcast input array from shape (4,1) into shape (4,), which has not been able to put the array in form (4,1) in a place where one expected form (4,) which is the same as saying (1,4) in this case.The solution is simple. Yeah. b is a size matrix (4,1), its transposed b.T will have dimensions (1.4) as we need. Therefore the following will work:import numpy as np
a = np.array(
[[-54., 25., 0., 0.],
[ 25., -54., 25., 0.],
[ 0., 25., -54., 25.],
[ 0., 0., 25., -54.]])
b = np.array(
[[ -0.8],
[ -1.6],
[ -2.4],
[-53.2]])
Aqui realizo la asignación que pides
a[:,1] = b.T
print(a)
The result is expected:array([[-54. , -0.8, 0. , 0. ],
[ 25. , -1.6, 25. , 0. ],
[ 0. , -2.4, -54. , 25. ],
[ 0. , -53.2, 25. , -54. ]])
Another option is to use b.flatten() to remove the nesting within the matrix-vector b and leave it as a simple sequence of numbers. In this example b.flatten() return [ -0.8, -1.6, -2.4, -53.2]which can also be assigned to the slice a[:, 1].Extension. Another solution is to modify the syntax on the left side of the mapping, and put this:a[: , 1:2] = b
In this case you're assigning b to the submarine a formed by all columns between 1 and 2. It's a single column, but the fact of having written it as a slice 1:2 makes numpy understand since a column vector b is valid for that assignment.