python 实现矩阵填充0的例子

yipeiwu_com6年前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 实现矩阵填充0的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

对django中render()与render_to_response()的区别详解

render()与render_to_response()均是django中用来显示模板页面的,但是在django1.3之后,render()便比render_to_response()...

Python基于scipy实现信号滤波功能

Python基于scipy实现信号滤波功能

​ 1.背景介绍 在深度学习中,有时会使用Matlab进行滤波处理,再将处理过的数据送入神经网络中。这样是一般的处理方法,但是处理起来却有些繁琐,并且有时系统难以运行Matl...

Python排序搜索基本算法之堆排序实例详解

Python排序搜索基本算法之堆排序实例详解

本文实例讲述了Python排序搜索基本算法之堆排序。分享给大家供大家参考,具体如下: 堆是一种完全二叉树,堆排序是一种树形选择排序,利用了大顶堆堆顶元素最大的特点,不断取出最大元素,并调...

深入解析神经网络从原理到实现

深入解析神经网络从原理到实现

1.简单介绍 在机器学习和认知科学领域,人工神经网络(artificial neural network,缩写ANN),简称神经网络(neural network,缩写NN)或类神经网...

python sort、sort_index方法代码实例

本文实例为大家分享了python sort、sort_index的具体代码,供大家参考,具体内容如下 对Series进行排序 #生成序列obj obj=pd.Series([4,9...