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!
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!
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.
Write
"myMatrix = " + arrayOfArrayToMatlabString(array)
to a.m
file, open it in matlab, and execute it.You can also call matlab directly from python:
The toolbox npy-matlab can read
*.npy
binary files into MATLAB.*.npy
files can be directly exported with the NumPy module. From the documentation:npy-matlab is a simple collection of M-files available from GitHub, with a 2-clause BSD licence.
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:
or the function syntax form (if you have the file path stored in a string):
I would probably use
numpy.savetxt('yourfile.mat',yourarray)
in Python and thenyourarray = load('yourfile.mat')
in MATLAB.You could write the matrix in Python to a CSV file and read it in MATLAB using csvread.