Kronecker Product in Python and Matlab

I tried to reproduce the result in Python from MATLAB. However, it seems I do not understand. 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 

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) 

As far as I was able to verify, everything is correct, so far the definition of L. According to MATLAB kron(Iy, Dx) (which should be a kronecker product), the matrix should be 35X35, but Python believes that it should be 7X7. 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 am I getting different results?

Thanks!

+4
source share
1 answer

Use sparse.kron for the Kronecker sparse matrix product.

numpy.kron does not handle sparse matrices. When using sparse matrices, it may not generate an error, but the return value will be incorrect.

+4
source

Source: https://habr.com/ru/post/953983/


All Articles