Main Content

Use MATLAB Arrays in Python

This example shows how to use MATLAB® arrays in Python®.

The matlab package provides new Python data types to create arrays that can be passed to MATLAB functions. The matlab package can create arrays of any MATLAB numeric or logical type from Python sequence types. Multidimensional MATLAB arrays are supported.

Create a MATLAB array in Python, and call a MATLAB function on it.

import matlab
from production_server import client
client_obj = client.MWHttpClient("http://localhost:9910")
x = matlab.double([1,4,9,16,25])
print(client_obj.myArchive.sqrt(x))

[[1.0,2.0,3.0,4.0,5.0]]

You can use matlab.double to create an array of doubles given a Python list that contains numbers. You can call a MATLAB function such as sqrt on x, and the return value is another matlab.double array.

Create a multidimensional array. The magic function returns a 2-D array to Python scope.

a = client_obj.myArchive.magic(6)
print(a)

[[35.0,1.0,6.0,26.0,19.0,24.0],[3.0,32.0,7.0,21.0,23.0,25.0],
 [31.0,9.0,2.0,22.0,27.0,20.0],[8.0,28.0,33.0,17.0,10.0,15.0],
 [30.0,5.0,34.0,12.0,14.0,16.0],[4.0,36.0,29.0,13.0,18.0,11.0]]

Call the tril function to get the lower triangular portion of a.

b = client_obj.myArchive.tril(a)
print(b)

[[35.0,0.0,0.0,0.0,0.0,0.0],[3.0,32.0,0.0,0.0,0.0,0.0],
 [31.0,9.0,2.0,0.0,0.0,0.0],[8.0,28.0,33.0,17.0,0.0,0.0],
 [30.0,5.0,34.0,12.0,14.0,0.0],[4.0,36.0,29.0,13.0,18.0,11.0]]

Related Topics