欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python 实现矩阵填充0的例子

时间:2021-08-28 09:28:06|栏目:Python代码|点击:

需求:

原矩阵

[[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)

总结:

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

上一篇:Python 实现图像逐像素点取邻域数据

栏    目:Python代码

下一篇:Python SMTP发送邮件遇到的一些问题及解决办法

本文标题:python 实现矩阵填充0的例子

本文地址:http://www.codeinn.net/misctech/170537.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有