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设计】。

相关文章

关于tf.nn.dynamic_rnn返回值详解

关于tf.nn.dynamic_rnn返回值详解

函数原型 tf.nn.dynamic_rnn( cell, inputs, sequence_length=None, initial_state=None, d...

Python的自动化部署模块Fabric的安装及使用指南

fabric是python2.5或者更高的库,可以通过ssh在多个host上批量执行任务.完成系统管理任务.它提供一套基本操作在本地和远程执行shell命令,或者上传下载文件,辅助提供用...

matplotlib实现热成像图colorbar和极坐标图的方法

matplotlib实现热成像图colorbar和极坐标图的方法

热成像图 %matplotlib inline from matplotlib import pyplot as plt import numpy as np def f(x,...

Python卸载模块的方法汇总

easy_install 卸载 通过easy_install 安装的模块可以直接通过  easy_install -m PackageName 卸载,然后删除\Python27...

Python是编译运行的验证方法

虽然Python被说成是一种解释型语言,但是实际上,Python源程序要先经过编译,然后才能运行。 与Java语言类似,Python源程序编译之后得到的是字节码,交由Python虚拟机来...