Python – Changing part of an array doesn’t work

Changing part of an array doesn’t work… here is a solution to the problem.

Changing part of an array doesn’t work

import numpy as np
def solve_eps(eps):
    A = np.array([[eps, 1, 0], [1, 0, 0], [0, 1, 1]])
    b = np.array([1 + eps, 1, 2])

m_21 = A[1, 0] / A[0, 0]
    m_31 = A[2, 0] / A[0, 0]

print("What A[1, :] should be:", A[1, :] - A[0, :] * m_21)
    A[1, :] = A[1, :] - A[0, :] * m_21
    print("But it won't assign it to the slice!!!!!", A[1, :])

If we run solve_eps(2), you will see that the slices are not assigned:

What A[1, :] should be: [ 0. -0.5 0. ]
But it won’t assign it to the slice!!!!! [0 0 0]

However, if you run:

A = np.array([[3, 1, 1], [2, 2, 2]])
A[1, :] = A[1, :] - (A[0, :] * 4)

A[1, :] = [-10, -2, -2]

What’s going on?

Solution

Set dtype=float: when defining A

A = np.array([[eps, 1, 0], [1, 0, 0], [0, 1, 1]], dtype=float)

The reason you failed to allocate is because you assigned float to an integer array.

As you can see, assigning integers to integer slices works well.

Related Problems and Solutions