Exchanging Complex Matrices Between MATLAB and Python

Vitality Learning
3 min readOct 8, 2024
Photo by Igor Omilaev on Unsplash

When working with complex matrices, you may need to transfer data between MATLAB and Python. This post will show how to save complex matrices in MATLAB and load them in Python, and how to do the reverse — save complex matrices in Python and load them in MATLAB.

Additionally, we’ll explore how to exchange multiple complex matrices between these two environments.

Step 1: Define and Save a Complex Matrix in MATLAB

First, define your complex matrix in MATLAB. In this example, we create a 2x3 complex matrix A:

A = [(1 + 1i) (3 - 4 * 1i); (2 + 2 * 1i) (-4 + 5 * 1i)];
save('A.mat', 'A', '-v4')

The -v4 flag ensures that the file is saved in an older MATLAB format. This format is widely compatible with various versions of MATLAB and other software, including Python.

Step 2: Load the Complex Matrix in Python

Once the file has been saved, you can load it in Python using the scipy.io module.

import scipy.io as sio

# Load the .mat file
Af = sio.loadmat('A.mat')

# Extract the matrix
A = Af.get('A')

# Print the matrix
print(A)

--

--

Vitality Learning

We are teaching, researching and consulting parallel programming on Graphics Processing Units (GPUs) since the delivery of CUDA. We also play Matlab and Python.