Matrix from Python to MATLAB

2019-01-21 18:38发布

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!

7条回答
欢心
2楼-- · 2019-01-21 19:21

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.

查看更多
Viruses.
3楼-- · 2019-01-21 19:22

You can also call matlab directly from python:

from mlabwrap import mlab
import numpy 
a = numpy.array([1,2,3])
mlab.plot(a)
查看更多
Evening l夕情丶
4楼-- · 2019-01-21 19:26

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.

查看更多
聊天终结者
5楼-- · 2019-01-21 19:29

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);
查看更多
狗以群分
6楼-- · 2019-01-21 19:38

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

查看更多
神经病院院长
7楼-- · 2019-01-21 19:40

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

查看更多
登录 后发表回答