53

I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this?

Thanks!

Amro
  • 123,847
  • 25
  • 243
  • 454

7 Answers7

76

If you use numpy/scipy, you can use the scipy.io.savemat function:

import numpy, scipy.io

arr = numpy.arange(9) # 1d array of 9 numbers
arr = arr.reshape((3, 3))  # 2d array of 3x3

scipy.io.savemat('c:/tmp/arrdata.mat', mdict={'arr': arr})

Now, you can load this data into MATLAB using File -> Load Data. Select the file and the arr variable (a 3x3 matrix) will be available in your environment.

Note: I did this on scipy 0.7.0. (scipy 0.6 has savemat in the scipy.io.mio module.) See the latest documentation for more detail

EDIT: updated link thanks to @gnovice.

Pani
  • 1,317
  • 1
  • 14
  • 20
ars
  • 120,335
  • 23
  • 147
  • 134
  • 1
    That link doesn't seem to work for me. Perhaps this one would work better: http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.savemat.html – gnovice Jul 07 '09 at 23:32
  • The link works fine at my end. But your link is better -- it's for the latest docs (0.7+) whereas mine was for 0.6, hence the different module (I have an old bookmark). Thanks gnovice! – ars Jul 07 '09 at 23:35
9

I think ars has the most straight-forward answer for saving the data to a .mat file from Python (using savemat). To add just a little to their answer, you can also load the .mat file into MATLAB programmatically using the LOAD function instead of doing it by hand using the MATLAB command window menu...

You can use either the command syntax form of LOAD:

load c:/tmp/arrdata.mat

or the function syntax form (if you have the file path stored in a string):

filePath = 'c:/tmp/arrdata.mat';
data = load(filePath);
Community
  • 1
  • 1
gnovice
  • 125,304
  • 15
  • 256
  • 359
  • 1
    +1; Neat! I don't use matlab enough, and always end up fumbling in the menus instead of just looking for the right command. Load would seem obvious. Ahem. :-) – ars Jul 08 '09 at 01:28
6

I wrote a small function to do this same thing, without need for numpy. It takes a list of lists and returns a string with a MATLAB-formatted matrix.

def arrayOfArrayToMatlabString(array):
    return '[' + "\n ".join(" ".join("%6g" % val for val in line) for line in array) + ']'

Write "myMatrix = " + arrayOfArrayToMatlabString(array) to a .m file, open it in matlab, and execute it.

Seth Johnson
  • 14,762
  • 6
  • 59
  • 85
6

I would probably use numpy.savetxt('yourfile.mat',yourarray) in Python and then yourarray = load('yourfile.mat') in MATLAB.

Jack
  • 10,943
  • 13
  • 50
  • 65
  • 1
    In MATLAB 2016b, this only works if you use `yourarray = load('yourfile.mat', '-ASCII')`. – Tokkot May 09 '19 at 13:29
4

You could write the matrix in Python to a CSV file and read it in MATLAB using csvread.

Jacob
  • 34,255
  • 14
  • 110
  • 165
  • I tried including a link to csvread (http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/csvread.html&http://www.google.com/search?hl=en&rlz=1C1GGLS_en-USUS294US304&q=matlab+csvread&aq=f&oq=&aqi=) in the answer. – Jacob Jul 07 '09 at 23:05
4

The toolbox npy-matlab can read *.npy binary files into MATLAB. *.npy files can be directly exported with the NumPy module. From the documentation:

>> a = rand(5,4,3);
>> writeNPY(a, 'a.npy');
>> b = readNPY('a.npy');
>> sum(a(:)==b(:))
ans =

    60

npy-matlab is a simple collection of M-files available from GitHub, with a 2-clause BSD licence.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
dingzeyuli
  • 41
  • 1
4

You can also call matlab directly from python:

from mlabwrap import mlab
import numpy 
a = numpy.array([1,2,3])
mlab.plot(a)
SiggyF
  • 22,088
  • 8
  • 43
  • 57