带有 numpy 数组问题的递归矩阵构造(广播?)

问题描述 投票:0回答:1

以下是寻找超立方矩阵的看似简单的递归。

递归定义为:

(Formula)

我尝试将其放入代码中,但我不断遇到 numpy 的广播问题。

我尝试不取前一个矩阵的大小,而是取 2 的幂来减少递归调用(对于单位矩阵的参数)。

import numpy as np
from numpy import linalg as LA

Q1 = np.array([[0, 1],
               [1, 0]])

def Qn(n):
    if n <= 1:
        return Q1
    else:
        return np.array([[Qn(n-1), np.identity(int(np.exp2(n-1)))],
                         [np.identity(int(np.exp2(n-1))), Qn(n-1)]])
    
Q3= Qn(3)

eig_value, eig_vectors = LA.eig(Q3)
print(eig_value)

Q1 是我的矩阵的基本情况。这应该很简单,但我一直遇到问题。

Traceback (most recent call last):
File "e:\Coding\Python\test.py", line 15, in <module>
Q3= Qn(3)
File "e:\Coding\Python\test.py", line 12, in Qn
return np.array([[Qn(n-1), np.identity(int(np.exp2(n-1)))],
ValueError: setting an array element with a sequence. The 
requested array has an inhomogeneous shape after 2 dimensions. The 
detected shape was (2, 2) + inhomogeneous part.

我收到此错误^^

python numpy recursion adjacency-matrix array-broadcasting
1个回答
0
投票

使用

np.block
代替
np.array
来组装分块矩阵。

import numpy as np
from numpy import linalg as LA

Q1 = np.array([[0, 1],
               [1, 0]])

def Qn(n):
    if n <= 1:
        return Q1
    else:
        Qnm1 = Qn(n-1)
        I = np.eye(int(np.exp2(n-1)))
        return np.block([[Qnm1, I], [I, Qnm1]])
    
Q3 = Qn(3)
© www.soinside.com 2019 - 2024. All rights reserved.