使矩阵平方并在numpy中填充所需的值 [英] Making a matrix square and padding it with desired value in numpy
问题描述
通常,我们可以具有任意大小的矩阵.对于我的应用程序,必须具有方矩阵.另外,虚拟条目应具有指定的值.我想知道是否有任何内置的numpy?
In general we could have matrices of arbitrary sizes. For my application it is necessary to have square matrix. Also the dummy entries should have a specified value. I am wondering if there is anything built in numpy?
或者是最简单的方法
矩阵X已经存在并且没有平方.我们要填充该值以使其平方.用虚拟给定值填充它.所有原始值将保持不变.
The matrix X is already there and it is not squared. We want to pad the value to make it square. Pad it with the dummy given value. All the original values will stay the same.
非常感谢
推荐答案
在LucasB的答案的基础上,该函数将填充具有给定值val
的任意矩阵M
,使其变为正方形:
Building upon the answer by LucasB here is a function which will pad an arbitrary matrix M
with a given value val
so that it becomes square:
def squarify(M,val):
(a,b)=M.shape
if a>b:
padding=((0,0),(0,a-b))
else:
padding=((0,b-a),(0,0))
return numpy.pad(M,padding,mode='constant',constant_values=val)
这篇关于使矩阵平方并在numpy中填充所需的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!