Home > Software design >  Problems with changing columns in a ndarray
Problems with changing columns in a ndarray

Time:12-08

So, I basically try to replace columns values in a matrix. The math im doing is basically the gram schmidt process. The problem is the change of the columns is not working properly. Better explained in example below code.

    for j in range(len(a)):
        a[:, j] = (a[:,j]/(math.sqrt(np.dot(a[:,j],a[:,j])))).reshape(-1,1).reshape(-1)

Values before the changes according to watches:

a[:,j] = [1 2 3 2 1]

(a[:,j]/(math.sqrt(np.dot(a[:,j],a[:,j])))).reshape(-1,1).reshape(-1) = [0.22 0.45 0.68 0.45 0.22]

After:

a[:,j]= [0 0 0 0]

CodePudding user response:

The only problem with your code is that you are initializing the array a with integers. Therefore, when you assign the result of the operation (which is an array of floats) to the jth column of the array, NumPy turns its elements into integers. You can solve it by adding dtype=np.float64 to the initialization of a:

a = np.array([[1, 2, 3, 2, 1] * 3], dtype=np.float64).reshape(3, 5)

Extra

This is a simpler approach for the operation you are performing:

import numpy as np

a = np.array([[1, 2, 3, 2, 1] * 3], dtype=np.float64).reshape(3, 5)

for idx, row in enumerate(a):
    a[idx] = row / np.sqrt(np.dot(row, row))
  • Related