Python和Matlab中的Kronecker产品 [英] Kronecker product in Python and Matlab

查看:172
本文介绍了Python和Matlab中的Kronecker产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从MATLAB中用Python复制结果.但是,我似乎无法正确地做到这一点.这是正确的MATLAB代码:

I was trying to reproduce a result in Python from MATLAB. However, I can't seem to get it right. This is the correct MATLAB code:

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

现在,这是Python代码:

Now, this is the Python code:

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)

据我所知,在定义L之前,一切都是正确的.根据MATLAB kron(Iy, Dx)(应该是kronecker产品),它应该产生35X35的矩阵,但是Python认为它应该是7X7矩阵.在更简单的计算中,两者都给出正确的答案:

As far I have been able to verify, everything is correct until the definition of L. According to MATLAB kron(Iy, Dx) (which is supposed to be the kronecker product) should produce a 35X35 matrix, but Python thinks it should be a 7X7 matrix. In simpler calculations, both give the correct answer:

Python:

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

array([[1, 2, 2, 4],
       [2, 4, 3, 6]])

MATLAB

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

ans = 1   2   2   4
      2   4   3   6

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

Why do I get different results?

谢谢!

推荐答案

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

Use sparse.kron for the Kronecker product of sparse matrices.

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

numpy.kron does not handle sparse matrices. When given sparse matrices, it might not generate an error, but the value it returns will not be correct.

这篇关于Python和Matlab中的Kronecker产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆