Main Content

Use MATLAB Arrays in Python

This example shows how to create a MATLAB® array in Python® and pass it as the input argument to the MATLAB sqrt function.

The matlab package provides constructors to create MATLAB arrays in Python. MATLAB Engine API for Python can pass such arrays as input arguments to MATLAB functions, and can return such arrays as output arguments to Python. You can create arrays of any MATLAB numeric or logical type from Python sequence types.

Create a MATLAB array from a Python list. Call the sqrt function on the array.

import matlab.engine
eng = matlab.engine.start_matlab()
a = matlab.double([1,4,9,16,25])
b = eng.sqrt(a)

The engine returns b, which is a 1-by-5 matlab.double array.

Create a multidimensional array. The magic function returns a 2-D matlab.double array to Python. Use a for loop to print each row on a separate line. (Press Enter again when you see the ... prompt to close the loop and print.)

a = eng.magic(6)
for x in a: print(x)

Call the tril function to get the lower triangular portion of a. Print each row on a separate line.

b = eng.tril(a)
for x in b: print(x)

Related Examples

More About