Python 和 Matlab 中的 Kronecker 产品

Rob*_*ith 5 python matlab numpy scipy

我试图从 MATLAB 在 Python 中重现结果。但是,我似乎无法正确理解。这是正确的 MATLAB 代码:

nx = 5;
ny = 7;

x = linspace(0, 1, nx); dx = x(2) - x(1);
y = linspace(0, 1, ny); dy = y(2) - y(1);

onex = ones(nx, 1);
oney = ones(ny, 1);

Dx = spdiags([onex -2*onex onex], [-1 0 1], nx, nx);
Dy = spdiags([oney -2*oney oney], [-1 0 1], ny, ny);

Ix = eye(nx); Iy = eye(ny);
L = kron(Iy, Dx);

size(L) % 35   35
Run Code Online (Sandbox Code Playgroud)

现在,这是 Python 代码:

nx = 5
ny = 7
x = linspace(0, 1, nx); dx = x[1] - x[0]
y = linspace(0, 1, ny); dy = y[1] - y[0]

onex = ones(nx)
oney = ones(ny)
Dx = sparse.dia_matrix( ([onex, -2*onex, onex], [-1,0,1] ), shape=(nx,nx))
Dy = sparse.dia_matrix( ([oney, -2*oney, oney], [-1,0,1] ), shape=(ny,ny))

Ix = eye(nx)
Iy = eye(ny)

L = kron(Iy, Dx)

L.shape # (7, 7)
Run Code Online (Sandbox Code Playgroud)

据我已经能够验证,一切都是正确的,直到 L 的定义。根据 MA​​TLAB kron(Iy, Dx)(应该是 kronecker 产品)应该产生一个 35X35 矩阵,但 Python 认为它应该是一个 7X7 矩阵。在更简单的计算中,两者都给出了正确的答案:

Python:

kron(array(([1,2],[2,3])), [1,2])

array([[1, 2, 2, 4],
       [2, 4, 3, 6]])
Run Code Online (Sandbox Code Playgroud)

MATLAB

kron([1 2; 2 3], [1 2]) 

ans = 1   2   2   4
      2   4   3   6
Run Code Online (Sandbox Code Playgroud)

为什么我得到不同的结果?

谢谢!

War*_*ser 5

使用sparse.kron稀疏矩阵的Kronecker积。

numpy.kron不处理稀疏矩阵。当给定稀疏矩阵时,它可能不会产生错误,但它返回的值将不正确。