使用numpy生成特定矩阵

时间:2018-03-10 14:25:55

标签: python numpy matrix

说n = 4:

然后我想生成以下矩阵:

1 0 0 0  1 0 0 1  1 0 1 1
0 1 0 0  1 1 0 0  1 1 0 1
0 0 1 0  0 1 1 0  1 1 1 0
0 0 0 1  0 0 1 1  0 1 1 1

你可以通过附加3个矩阵来获得,(A0,A1,A2)horizo​​ntaly

如果我'=

0 0 0 1
1 0 0 0
0 1 0 0
0 0 1 0

然后:

A0 = I'^0
A1 = I'^1 + I'^0
A2 = I'^2 + I'^1 + I'^0

如何使用numpy有效地实现这一目标?

编辑:

当n = 3时为前

我会变成

0 0 1
1 0 0
0 1 0

并且所需的结果将是A0附加到A1

2 个答案:

答案 0 :(得分:1)

您可以使用模运算符:

>>> n = 4
>>> i,j,k = np.ogrid[:n, :n-1, :n]
>>> ((j-i+k)%n <= j).reshape(n, -1).view(np.int8)
array([[1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1],
       [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1],
       [0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0],
       [0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1]], dtype=int8)

夹在0 s和1 s:

列之间
>>> i, jk = np.ogrid[:n, :n*n - n + 2]
>>> j, k = divmod(jk + n - 1, n)
>>> print(((j-i+k-1)%n < j).view(np.int8))
[[0 1 0 0 0 1 0 0 1 1 0 1 1 1]
 [0 0 1 0 0 1 1 0 0 1 1 0 1 1]
 [0 0 0 1 0 0 1 1 0 1 1 1 0 1]
 [0 0 0 0 1 0 0 1 1 0 1 1 1 1]]

答案 1 :(得分:0)

使用一些列表推导(我假设你知道这个概念,否则请谷歌它,它在这种情况下真的很有帮助)和np.linalg.matrix_powernp.sumnp.concatenate

In [47]: n = 4
In [48]: np.concatenate(
    ...:     [
    ...:         np.sum(
    ...:             [np.linalg.matrix_power(I, i) for i in range(exp+1)],
    ...:             axis=0  # sum them correct over the axis not the whole data
    ...:         )
    ...:         for exp in range(n-1)
    ...:     ],
    ...:     axis=1  # concat horizontal not vertical
    ...: )
Out[48]:
array([[1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1],
       [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1],
       [0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0],
       [0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1]])

这也可以与其他n值一起使用:

In [49]: n = 5
In [50]: np.concatenate(
    ...:     [
    ...:         np.sum([np.linalg.matrix_power(I, i) for i in range(exp+1)], axis=0)
    ...:         for exp in range(n-1)
    ...:     ], axis=1)
Out[50]:
array([[1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1],
       [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1],
       [0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1],
       [0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1]])

In [51]: n = 3
In [52]: np.concatenate(
    ...:     [
    ...:         np.sum([np.linalg.matrix_power(I, i) for i in range(exp+1)], axis=0)
    ...:         for exp in range(n-1)
    ...:     ], axis=1)
Out[52]:
array([[1, 0, 0, 0, 1, 0, 0, 1],
       [0, 1, 0, 0, 1, 1, 0, 0],
       [0, 0, 1, 0, 0, 1, 1, 0],
       [0, 0, 0, 1, 0, 0, 1, 1]])

编辑:

您可以通过眼睛生成您所需的I

In [68]: n=3

In [69]: I = np.eye(n, k=-1) + np.eye(n, k=n-1)

In [70]: I
Out[70]:
array([[0., 0., 1.],
       [1., 0., 0.],
       [0., 1., 0.]])