python 实现矩阵填充 0

python 实现矩阵填充 0


  • 需求:

    原矩阵

[[1 2 3]
 [4 5 6]
 [7 8 9]]

在原矩阵元素之间填充元素 0,得到

[[1. 0. 2. 0. 3.]
 [0. 0. 0. 0. 0.]
 [4. 0. 5. 0. 6.]
 [0. 0. 0. 0. 0.]
 [7. 0. 8. 0. 9.]]

  • 思路:

    先求出扩充矩阵的维度,再按照每一行每一列遍历,根据元素的索引规律依次赋值,最终实现新的扩充矩阵。这个思路实现如下:

import numpy as np

def PadMat(Ndim, Mat):
	Brow = Bcol = 2*Ndim-1
	B = np.zeros([Brow, Bcol])
	for row in range(Brow):
		if row%2 == 0:
			for col in range(Bcol):
				if col%2 == 0:
					pos_c = int(col/2)
					pos_r = int(row/2)
					# print(row, col)
					B[row, col] = Mat[pos_r, pos_c]
				else:
					B[row, col] = 0
	return B


# A = np.arange(9) + 1
# A = A.reshape([3, 3])
A = np.arange(16) + 1
A = A.reshape([4, 4])
# print(A.shape[0])
N = Arow = Acol = A.shape[0]

NewMat = PadMat(Ndim=N, Mat=A)
print(A)
print(NewMat)

  • 总结:

    这个思路很直接,但是循环套循环是一个很笨的办法,而且遍历也很慢。不知道网友有什么好的思路吗?

猜你喜欢

转载自blog.csdn.net/qq_23947237/article/details/88652246