Home > Blockchain >  Transpose only the matrix values with numpy if multiple of 3
Transpose only the matrix values with numpy if multiple of 3

Time:11-18

I have a 5x5 matrix and I would like to transpose all values but those which are multiple of 3, they will transpose with the following structure:

If multiple of 3: M[i, j] = (3 * j i)**2 Otherwise: M[i, j] = M[j, i]

M is the matrix, i and j the index of the rows and columns.

The matrix consists of 25 values from 1 to 100 without repetition.

I have the following code and now I have created the condition for the values that are multiple of 3. I don't know how to create the part where it should do:

M[i, j] = (3 * j   i)**2

I put 0 as a result just to show the spots where the (3 * j i)**2 should appear.

import numpy as np
M = np.random.randint(1, 100, size=25).reshape(5, 5)
print("Matrix 5x5 original")
print(M)
print("Matrix transposed")
M = np.transpose(M)
M[M % 3 == 0] = 0
print(M)

enter image description here

CodePudding user response:

You need to convert the mask M % 3 == 0 to indices. Something like this should work:

M = M.T
i, j = np.where(M % 3 == 0)
M[i, j] = (3 * j   i)**2
  • Related