Home > Back-end >  assign the constant value to the each respective index postion in the 2D matrix
assign the constant value to the each respective index postion in the 2D matrix

Time:11-09

I am obtaining undesired results in python.

Goal: I want to assign the constant value to the respective element of the 2D matrix. I have indey list of the row and colum

idx_container_phi = [22, 19, 25, 23, 22, 21, 22, 30, 16, 12, 14] # row index
idx_container_theta = [22, 19, 10, 23, 22, 7, 22, 8, 16, 19, 11] # column index
thickness = 0.85
sphere_pixels  = 36

What I have done: (1) First I have initialized the 2D matrix with certain shape.

matrix_thickness = np.array([ [0]*sphere_pixels for i in range(sphere_pixels)])

(2) I initialized for loop which excexutes till the range of the index list and assign the constant value.

for j in range(len(idx_container_phi)):
    matrix_thickness[idx_container_phi[j]-1][idx_container_theta[j]-1] = matrix_thickness[idx_container_phi[j]-1][idx_container_theta[j]-1]   thickness

However, while running the code, I got the matrix with null values in every element. How can I assign the constant value to the each respective index postion in the 2D matrix?

Desire Output: Matrix of the size 36 X 36. I want to assign the value of thickness (0.85) to the index position [22, 22], [19, 19], [25, 10], [23, 23], [22, 22], [21, 7], [22, 22], [30, 8], [16, 16], [12, 19], [14, 11].

If any index comes two times, for ex. [22, 22], [22, 22], then in this case, value of the thickness (0.85) should be added (0.85 0.85 = 1.70).

CodePudding user response:

This should result in the array you are searching for:

idx_container_phi = [1, 7, 3, 4, 1] # row index
idx_container_theta = [3, 5, 2, 4, 3] # column index
thickness = 0.85
sphere_pixels  = 10

matrix_thickness = np.zeros(shape=(sphere_pixels, sphere_pixels))

for row, col in zip(idx_container_phi, idx_container_theta):
    matrix_thickness[row, col]  = thickness
print(matrix_thickness)

Output:

[[0.   0.   0.   0.   0.   0.   0.   0.   0.   0.  ]
 [0.   0.   0.   1.7  0.   0.   0.   0.   0.   0.  ]
 [0.   0.   0.   0.   0.   0.   0.   0.   0.   0.  ]
 [0.   0.   0.85 0.   0.   0.   0.   0.   0.   0.  ]
 [0.   0.   0.   0.   0.85 0.   0.   0.   0.   0.  ]
 [0.   0.   0.   0.   0.   0.   0.   0.   0.   0.  ]
 [0.   0.   0.   0.   0.   0.   0.   0.   0.   0.  ]
 [0.   0.   0.   0.   0.   0.85 0.   0.   0.   0.  ]
 [0.   0.   0.   0.   0.   0.   0.   0.   0.   0.  ]
 [0.   0.   0.   0.   0.   0.   0.   0.   0.   0.  ]]

CodePudding user response:

So there is also another way to do this. I got to know that by default numpy array bydefault initializes with dtype = int. Therefore even after assigning the constant value (which is float value) it changes to the interger value.

Mentioning dtype=float works and gives desired output.

matrix_thickness = np.array([ [0]*sphere_pixels for i in range(sphere_pixels)], dtype=float)
  • Related