# Pass sparse matrices to and from python within matlab

## Alec Jacobson

## March 28, 2021

Matlab has a (clunky) interface to python. Passing data can be awkward. There is no built in support (AFAIK) for passing matlab sparse matrices to scipy sparse matrices.

For starters, *don't do this*:

```
A = sprandn(10000,10000,0.0001);
pyA = py.scipy.sparse.csc_matrix(full(A));
```

casting to full defeats the purpose of sparse storage.

Instead you can build a scipy sparse matrix directly. In scipy, you must explicitly specify the storage, for this example I'll use CSC:

```
[AI,AJ,AV] = find(A);
pyA = py.scipy.sparse.csc_matrix({AV,{uint64(AI-1) uint64(AJ-1)}},{uint64(size(A,1)),uint64(size(A,2))});
```

Notice the `-1`

on the indices. Python uses 0-based indexing.

To convert back from a python sparse matrix to a matlab sparse matrix, a general approach is:

```
coo = pyA.tocoo;
A = sparse(double(coo.row+1),double(coo.col+1),double(coo.data),double(coo.shape{1}),double(coo.shape{2}));
```

Rebuilding the sparse matrix directly from the CSC `indices`

and `indptr`

is also possible (i.e., avoiding the copy), but this version will happily work regardless of the original storage type of `pyA`

.