# Write a matrix to file in matlab, read a matrix from file in python with numpy

## Alec Jacobson

## January 02, 2011

Since matlab and numpy seem to disagree about csv, the easiest way I've found to export a matlab matrix to file and then read it in python with numpy is calling from matlab:
```
save -ascii 'A.txt' A
```

Then in python with numpy:
```
from numpy import *
A = genfromtxt('A.txt');
```

To go the other direction use from python with numpy:
```
from numpy import *
savetxt("A.txt", A)
```

And from matlab:
```
load -ascii A.txt A
```

When I use these to save a matrix from matlab to file, read it into a numpy array then save it out to file and load it back into matlab I get error between the two matrices on the order of 1e-15 (i.e. exact up to double precision with the default settings).
The above code works for 1D and 2D arrays/vectors/dense matrices. Hopefully I will find something just as easy for sparse matrices.
source (although it's rather incomplete on this issue) or better source