"Converting" Numpy arrays to Matlab and vice versa


Question

I am looking for a way to pass NumPy arrays to Matlab.

I've managed to do this by storing the array into an image using scipy.misc.imsave and then loading it using imread, but this of course causes the matrix to contain values between 0 and 256 instead of the 'real' values.

Taking the product of this matrix divided by 256, and the maximum value in the original NumPy array gives me the correct matrix, but I feel that this is a bit tedious.

is there a simpler way?

1
32
6/12/2012 1:03:23 PM

Accepted Answer

Sure, just use scipy.io.savemat

As an example:

import numpy as np
import scipy.io

x = np.linspace(0, 2 * np.pi, 100)
y = np.cos(x)

scipy.io.savemat('test.mat', dict(x=x, y=y))

Similarly, there's scipy.io.loadmat.

You then load this in matlab with load test.

Alteratively, as @JAB suggested, you could just save things to an ascii tab delimited file (e.g. numpy.savetxt). However, you'll be limited to 2 dimensions if you go this route. On the other hand, ascii is the universial exchange format. Pretty much anything will handle a delimited text file.

44
6/12/2012 1:12:28 PM

A simple solution, without passing data by file or external libs.

Numpy has a method to transform ndarrays to list and matlab data types can be defined from lists. So, when can transform like:

np_a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
mat_a = matlab.double(np_a.tolist())

From matlab to python requires more attention. There is no built-in function to convert the type directly to lists. But we can access the raw data, which isn't shaped, but plain. So, we use reshape (to format correctly) and transpose (because of the different way MATLAB and numpy store data). That's really important to stress: Test it in your project, mainly if you are using matrices with more than 2 dimensions. It works for MATLAB 2015a and 2 dims.

np_a = np.array(mat_a._data.tolist())
np_a = np_a.reshape(mat_a.size).transpose()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon