动态地在numpy中构造一个特殊矩阵 [英] Constructing a special matrix in numpy dynamically
问题描述
所以我的目标是,给定矩阵s
的大小,我试图创建一个如下所示的矩阵,但大小为sxs
:
So my objective is the following, given the size of the matrix s
, I am attempting to create a matrix that looks like the following, but for size sxs
:
[1 1 0]
[1 1 1]
[0 1 1]
对于4x4的大小,它看起来类似于以下内容:
For the size of 4x4, it would look something like the following:
[1 1 0 0]
[1 1 1 0]
[0 1 1 1]
[0 0 1 1]
因此,您可以观察到一个模式:有s-1
个重叠的迷你2x2
个矩阵.
Therefore you can observe a pattern: there are s-1
number of overlapping mini 2x2
ones matrices.
我当时正在考虑创建一个2x2
个1矩阵,然后使用像B[:-1,:-1] = ones_matrix
这样的动态引用(用于循环吗?),其中B
是大小为sxs
的零矩阵.但是我不确定如何在此处合并for循环,因为如果我们说一个4x4
矩阵,那么我们将必须以三种方式引用B
:B[:-1,:-1] = ones_matrix, B[1:-1,1:-1] = ones_matrix, B[2:,2:]=ones_matrix
.而且我想不出一种方法来动态处理n
大小的零矩阵.也许还有另一种方法可以做到这一点?
I was thinking of creating a 2x2
ones matrix and then by using a dynamic referencing (for loop?) like B[:-1,:-1] = ones_matrix
, where B
is the zeros matrix of size sxs
. But I am not sure how to incorporate a for loop here, because if we take say a 4x4
matrix, then we would have to reference B
in three ways like so: B[:-1,:-1] = ones_matrix, B[1:-1,1:-1] = ones_matrix, B[2:,2:]=ones_matrix
. And I can't figure out a way to do that dynamically for n
-sized zeros matrix. Is there perhaps another way to do this?
推荐答案
方法#1:与其一堆2x2矩阵相比,将它看成三个对角线1并结合起来比较容易:
Method #1: Instead of a bunch of 2x2 matrices, it might be easier to look at it as three diagonals of 1 and combine those:
>>> s = 3
>>> np.diag([1]*s,0) + np.diag([1]*(s-1),-1) + np.diag([1]*(s-1), 1)
array([[1, 1, 0],
[1, 1, 1],
[0, 1, 1]])
>>> s = 4
>>> np.diag([1]*s,0) + np.diag([1]*(s-1),-1) + np.diag([1]*(s-1), 1)
array([[1, 1, 0, 0],
[1, 1, 1, 0],
[0, 1, 1, 1],
[0, 0, 1, 1]])
方法2 :(受Divankar的回答启发),我们可以根据距中心的距离进行思考:
Method #2: (inspired by Divankar's answer), we can think in terms of distance from the centre:
>>> s = 4
>>> i,j = np.indices((s,s))
>>> (abs(i-j) <= 1).astype(int)
array([[1, 1, 0, 0],
[1, 1, 1, 0],
[0, 1, 1, 1],
[0, 0, 1, 1]])
方法3:我们可以利用tril
或triu
进行一些算术:
Method #3: we could take advantage of tril
or triu
and do some arithmetic:
>>> m = np.tril(np.ones((s,s)),1)
>>> m * m.T
array([[ 1., 1., 0., 0., 0.],
[ 1., 1., 1., 0., 0.],
[ 0., 1., 1., 1., 0.],
[ 0., 0., 1., 1., 1.],
[ 0., 0., 0., 1., 1.]])
>>> m = np.tril(np.ones((s,s)),2)
>>> m * m.T
array([[ 1., 1., 1., 0., 0.],
[ 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1.],
[ 0., 1., 1., 1., 1.],
[ 0., 0., 1., 1., 1.]])
这篇关于动态地在numpy中构造一个特殊矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!