Sparse Matrices in Python from Matlab

You can’t pass sparse matrices from Matlab to Python, so you have to have enough RAM to hold the full matrix and probably a copy or two of it. This post shows how it could be done, and we hope that the Mathworks will improve the passing of variables in future releases of Matlab.

All commands are issued in Matlab.

a = eye(5);
A = py.numpy.reshape(a(:)',size(a));
As = py.scipy.sparse.csc_matrix(A)

As =
Python csc_matrix with properties:

dtype: [1x1 py.numpy.dtype]
has_sorted_indices: 1
nnz: 5
shape: [1x1 py.tuple]
maxprint: 50
indices: [1x1 py.numpy.ndarray]
data: [1x1 py.numpy.ndarray]
indptr: [1x1 py.numpy.ndarray]
format: [1x1 py.str]
(0, 0) 1.0
(1, 1) 1.0
(2, 2) 1.0
(3, 3) 1.0
(4, 4) 1.0

Leave a Comment