5 Best Ways to Convert Python NumPy Arrays to MATLAB

πŸ’‘ Problem Formulation:

Transferring data between different programming environments is a common task in scientific computing. For instance, a user may have a NumPy array in Python that they want to use within MATLAB. The desired outcome is to have the NumPy array data accessible in MATLAB’s workspace as a MATLAB array. This article discusses the most effective ways to achieve this conversion.

Method 1: Use the scipy.io.savemat Function

Scipy’s io module provides a convenient way to handle various file formats that are commonly used in scientific computing. The savemat function is specifically designed for saving MATLAB .mat files. This method entails creating a dictionary of variable names and array data and then saving this dictionary as a .mat file.

Here’s an example:

import numpy as np
from scipy.io import savemat

# Create a NumPy array
np_array = np.array([1, 2, 3])

# Save to .mat file
savemat('array.mat', {'array': np_array})

Output: A .mat file named ‘array.mat’ is created with the NumPy array.

The above code snippet demonstrates the usage of savemat from scipy.io to save a NumPy array to a file that can be loaded in MATLAB. The resulting file ‘array.mat’ can then be opened in the MATLAB workspace using the load function.

Method 2: Use the MATLAB Engine for Python

MATLAB provides a Python package called MATLAB Engine which allows calling MATLAB functions from Python. With this method, you can start a MATLAB session, pass the NumPy array directly to MATLAB, and then use it within MATLAB like a native array.

Here’s an example:

import matlab.engine
import numpy as np

# Start MATLAB engine
eng = matlab.engine.start_matlab()

# Create a NumPy array
np_array = np.array([4, 5, 6])

# Convert and transfer to MATLAB
mat_array = matlab.double(np_array.tolist())

# Put the array into MATLAB's workspace
eng.workspace['myArray'] = mat_array

Output: The MATLAB workspace will contain a variable myArray with the NumPy array’s values.

This code snippet illustrates how one can move data from Python to MATLAB using the MATLAB Engine. By converting the NumPy array to a MATLAB array type via matlab.double(), the data can be directly assigned to a variable in the MATLAB workspace.

Method 3: Use the hdf5storage Package

The Python package hdf5storage can save data in the HDF5 format, which is also supported by MATLAB. This approach allows saving NumPy arrays in a format that MATLAB can easily understand without the need for MAT files.

Here’s an example:

import numpy as np
import hdf5storage

# Create a NumPy array
np_array = np.array([7, 8, 9])

# Save to .h5 file
hdf5storage.write({'np_array': np_array}, '.', 'array.h5', store_python_metadata=False, matlab_compatible=True)

Output: An .h5 file named ‘array.h5’ is created, which can be loaded in MATLAB.

The code snippet showcases how the hdf5storage library can save a NumPy array in a way that is compatible with MATLAB. The store_python_metadata=False and matlab_compatible=True options make sure that MATLAB can interpret the saved data.

Method 4: Use a CSV File for Data Exchange

Using comma-separated values (CSV) files is a simple and universal method for data exchange. Both Python and MATLAB can read and write CSV files which makes this method straightforward for transferring array data between the two environments.

Here’s an example:

import numpy as np

# Create a NumPy array
np_array = np.array([10, 11, 12])

# Save to CSV file
np.savetxt("array.csv", np_array, delimiter=",")

Output: A CSV file named ‘array.csv’ is created.

The code snippet demonstrates the saving of a NumPy array to a CSV file using np.savetxt(). This file can then be easily imported into MATLAB using csvread or readtable functions.

Bonus One-Liner Method 5: Inline Conversion Using %%python Magic Command in MATLAB

For those who use MATLAB’s integrated development environment, you can directly convert and import NumPy array using the built-in %%python magic command without the need for any file-based conversion.

Here’s an example:

%python
import numpy as np
py_array = np.array([13, 14, 15])

Output: Use matlab.array(py_array.tolist()) in the command window to have NumPy array in MATLAB.

This code is executed within MATLAB’s command window using the %%python magic command, resulting in the creation of a Python variable that can be converted to a MATLAB array.

Summary/Discussion

  • Method 1: Use the scipy.io.savemat Function. It’s natively supported by scipy and is efficient for saving multiple variables. However, this requires an additional dependency in scipy if it’s not already installed.
  • Method 2: Use the MATLAB Engine for Python. This allows seamless transfer of data but requires MATLAB Engine for Python, which might not be suitable for all users due to licensing or MATLAB version compatibility.
  • Method 3: Use the hdf5storage Package. This preserves MATLAB compatibility and HDF5 is a versatile format, yet the method necessitates the hdf5storage library and has additional complexity for very simple data transfers.
  • Method 4: Use a CSV File for Data Exchange. It is very simple and doesn’t rely on any complex libraries, but it also lacks support for multi-dimensional arrays and might be less efficient for large datasets.
  • Method 5: Inline Conversion Using %%python Magic Command in MATLAB. It is perhaps the simplest for users directly working within MATLAB. However, this method is restricted to MATLAB’s environment and might not be suitable for large-scale or automated data transfer tasks.