Main Content

Pass Data Between MATLAB and Python from MATLAB

When you call a Python® function in MATLAB®, the Python interface converts the MATLAB input data into types that best represent the data in the Python language. The Python interface also converts some returned Python data into MATLAB data types.

Pass Data from MATLAB to Python

When you pass data from MATLAB to Python, the resulting Python type depends on whether the MATLAB data is a scalar value or an array.

Pass Scalar Value from MATLAB to Python

In MATLAB, when you pass a scalar value as input to a Python function, the Python interface automatically converts the data into the equivalent Python data type.

MATLAB Input Type
(for Scalar Values Only)

Resulting Python Data Type

Examples

double (real)
single (real)

float (default) or int

Use Python Numeric Variables in MATLAB

By default, the Python interface converts type double or single to Python float. However, for integer values based on Python type hints, the Python interface can convert type double or single to Python int.

double (complex)
single (complex)

complex

z = complex(1,2);
py.cmath.polar(z)
ans = 
  Python tuple with values:

    (2.23606797749979, 1.1071487177940904)

int8
uint8
int16
uint16
int32
uint32
int64
uint64

int

Use Python Numeric Variables in MATLAB

NaN

float("nan")

n = NaN;
py.float(n)
ans = 

  Python float with properties:

    imag: 0
    real: NaN

    nan

Inf

float("inf")

i = Inf;
py.float(i)
ans = 

  Python float with properties:

    imag: 0
    real: Inf

    inf

string scalar
char vector

str

Use Python str Variables in MATLAB

<missing> value in string
string(missing)

"None" value in str

s = string(missing);
py.str(s)
ans = 

  Python str with no properties.

    None

logical

bool

b = true;
py.type(b)
ans = 

  Python type with no properties.

    <class 'bool'>

dictionary
struct

dict

Use Python Dictionaries in MATLAB

table
timetable

pandas.DataFrameUse Python Pandas DataFrames in MATLAB
datetime

datetime.datetime

Use Python Datetime Types in MATLAB
duration

datetime.timedelta

Use Python Duration Types in MATLAB

Python object — py.type

type

-

function handle @py.module.function, to Python functions only

module.function

Pass Python Function to Python map Function

Pass Array Data from MATLAB to Python

In MATLAB, when you pass a MATLAB array as input to a Python function and the NumPy module is available in the Python environment, the Python interface automatically converts the array to a Python NumPy array. If the NumPy module is not available when you pass a MATLAB array as input to a Python function, the Python interface handles vector input as it does matrix input—the Python interface converts these inputs to Python memoryview objects. (since R2025a)

Before R2025a: When you pass a MATLAB vector with or without the NumPy package to a Python function, the Python interface converts the vector to a Python array.array object.

MATLAB Input Array Type (for Array Data Only)

Resulting Python Data Type with NumPy

double (real)

numpy.array(dtype=np.float64)

single (real)

numpy.array(dtype=np.float32)

int8 (real)

numpy.array(dtype=np.int8)

uint8 (real)

numpy.array(dtype=np.uint8)

int16 (real)

numpy.array(dtype=np.int16)

uint16 (real)

numpy.array(dtype=np.uint16)

int32 (real)

numpy.array(dtype=np.int32)

uint32 (real)

numpy.array(dtype=np.uint32)

int64 (real)

numpy.array(dtype=np.int64)

uint64 (real)

numpy.array(dtype=np.uint64)

double (complex)

numpy.array(dtype=np.complex128)

single (complex)

numpy.array(dtype=np.complex64)

logical

numpy.array(dtype=np.bool)

char vector

str

cell vector

tuple

1-by-N or M-by-1 string vector

list

datetime array

numpy.datetime64 array

duration array

numpy.timedelta64 array

char matrix
cell matrix
M-by-N string array where both M and N are greater than 1

No automatic conversion.

If NumPy is not installed and a numeric MATLAB array is passed to Python, the Python interface creates a memoryview object that points to the array contents. This memoryview object implements the Python buffer protocol and does not make a copy of the array. In this example, an array.array is constructed from the memoryview object created from the MATLAB array.

mArr = [1,2,3];
pyArr = py.array.array('d',mArr);

Explicitly Convert MATLAB Types to Python Types

While the Python interface does not automatically convert multidimensional MATLAB string data, you can explicitly convert the data to a Python data type.

MATLAB Type

Resulting Python Type

MATLAB Conversion Function

string array

NumPy StringDType array

pystringarray

Unsupported MATLAB Types

These MATLAB types are not supported in Python:

  • Sparse arrays

  • Nonscalar struct arrays

  • categorical

  • containers.Map

  • MATLAB objects

  • matlab.metadata.Class (py.class)

Pass Data from Python to MATLAB

When you call Python functions from within MATLAB, the functions can return data of any data type. Depending on the data type returned by the Python function, the Python interface might automatically convert the output into a MATLAB data type. If the Python interface does not automatically convert the data, the Python function returns output of a Python data type, which you can then manually convert into a MATLAB data type.

Return Scalar Value from Python to MATLAB

When a Python function returns a scalar value of any of these Python data types, the Python interface automatically converts the value into these MATLAB types.

Python Return Type, as Displayed in Python

Resulting MATLAB Data Type
(for Scalar Values Only)

float

double

complex

Complex double

bool

logical

datetime

datetime

str object in pandas.DataFrame
str object in dict

string

Explicitly Convert Python Types to MATLAB Types

When a Python function returns any other type of data, the Python interface does not automatically convert the data. You can explicitly convert Python data types to MATLAB types using these MATLAB functions.

Python Return Type or Protocol, as Displayed in MATLAB

MATLAB Conversion Function

Examples

py.str

string
char

Use Python str Variables in MATLAB

Object with __str__ method

char

py.help('datetime.date.__str__')
Help on wrapper_descriptor in datetime.date:

datetime.date.__str__ = __str__(self, /) unbound datetime.date method
    Return str(self).
d = py.datetime.date(...
    int32(2020),int32(3),int32(4));
char(d)
ans = '2020-3-04'

py.int
py.long
py.float

double
single
int8
uint8
int16
uint16
int32
uint32
int64
uint64

Use Python Numeric Variables in MATLAB
py.bool

logical
double
single
int8
uint8
int16
uint16
int32
uint32
int64
uint64

x = py.bool(true);
double(x)
ans =

     1

py.bytes

uint8

b = py.bytes("MATLAB",'utf-8');
uint8(b)
ans =

  1×6 uint8 row vector

   77   65   84   76   65   66

py.array.array
py.memoryview

double
single
int8
uint8
int16
uint16
int32
uint32
int64
uint64

Use Python Numeric Variables in MATLAB

py.numpy.ndarray

double
single
int8
uint8
int16
uint16
int32
uint32
int64
uint64
string

Convert Python ndarray to MATLAB Array

py.list
py.tuple

double
single
int8
uint8
int16
uint16
int32
uint32
int64
uint64
logical
string
cell

Use Python list Variables in MATLAB
Use Python tuple Variables in MATLAB

For more information, see Error Converting Elements of list or tuple.

py.dict and other objects that implement the mapping protocol

dictionary
struct

Use Python Dictionaries in MATLAB
py.pandas.DataFrame

table
timetable

Use Python Pandas DataFrames in MATLAB

py.datetime.datetime
py.numpy.datetime64

datetime

Use Python Datetime Types in MATLAB

py.datetime.timedelta
py.numpy.timedelta64

duration

Use Python Duration Types in MATLAB

Unsupported Python Types

The Python enum type is not supported in MATLAB.

Convert Python ndarray to MATLAB Array

If the output of a Python function has a type, such as numpy.ndarray, that implements the Python buffer protocol, then MATLAB displays:

  • The actual Python type.

  • The underlying data.

  • The corresponding MATLAB conversion function. Use this function to fully convert the Python object to a MATLAB array.

For example, suppose a Python function returns this array p:

p = 

  Python ndarray:

     8     1     6
     3     5     7
     4     9     2

    Use details function to view the properties of the Python object.

    Use double function to convert to a MATLAB array.

Convert p to a MATLAB matrix M by using the suggested conversion function.

M = double(p)
M = 3×3    
     8     1     6
     3     5     7
     4     9     2

Get specific information about the Python properties of p.

details(p)
    py.numpy.ndarray handle with properties:

           T: [1×1 py.numpy.ndarray]
        base: [1×1 py.NoneType]
      ctypes: [1×1 py.numpy.core._internal._ctypes]
        data: [1×3 py.memoryview]
       dtype: [1×1 py.numpy.dtype[float64]]
       flags: [1×1 py.numpy.flagsobj]
        flat: [1×1 py.numpy.flatiter]
        imag: [1×1 py.numpy.ndarray]
    itemsize: [1×1 py.int]
      nbytes: [1×1 py.int]
        ndim: [1×1 py.int]
        real: [1×1 py.numpy.ndarray]
       shape: [1×2 py.tuple]
        size: [1×1 py.int]
     strides: [1×2 py.tuple]

  Methods, Events, Superclasses

If the Python module provides content in its __doc__ attribute, then MATLAB links to that information.

See Also

Topics