Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kronecker product in Python and 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

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 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?

Thanks!

like image 974
Robert Smith Avatar asked Jun 11 '13 02:06

Robert Smith


1 Answers

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

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.

like image 167
Warren Weckesser Avatar answered Sep 28 '22 23:09

Warren Weckesser