Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

python - Inset a matrix of zeros across another matrix's diagonal

Watered down example

Consider I have the following matrix A,

1  2  4  3
1  7  3  6
2  4  1  1
6  9  3  6

I would want to convert it to the matrix B which looks like,

0  0  4  4
0  0  3  6
2  4  0  0
6  9  0  0

So basically I would want to have, let's say a 2x2 matrix of zeros in the diagonal of the 4x4 matrix given above.

Need for a general solution

What i have provided above is just an example and I am going to use (1296, 1296) sized matrix as input and I want to inset a 3x3 matrix of zeros inside its diagonal.

What I have done so far?

A simple range based loop and then setting values to zero like so,

for i in range(0, mat.shape[0] - 1, 3):
    mat[i][i] = 0
    mat[i][i + 1] = 0
    mat[i][i + 2] = 0
    mat[i + 1][i] = 0
    mat[i + 1][i + 1] = 0
    mat[i + 1][i + 2] = 0
    mat[i + 2][i] = 0
    mat[i + 2][i + 1] = 0
    mat[i + 2][i + 2] = 0

I completely understand that this is a very crude and nasty way to do it. Please suggest a fast and "numpy" way of doing this.

question from:https://stackoverflow.com/questions/65846715/inset-a-matrix-of-zeros-across-another-matrixs-diagonal

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could try something like this:

start=0
stop=1296
step=3
for i in np.arange(start=start, stop=stop, step=step):
    mat[i:i+step, i:i+step] = 0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...