Call a Python Function

5 views (last 30 days)
bafflingbill23
bafflingbill23 on 28 Apr 2016
Answered: Raghava S N on 26 Nov 2024 at 5:59
I am trying to call a Python function and then return that data to the workspace. The function I am calling has two input parameters, a 2d array and a list. I need the function to return the updated 2d array and updated list.
I looked, but I just cannot figure out how to do it.
Thanks so much in advance!!

Answers (1)

Raghava S N
Raghava S N on 26 Nov 2024 at 5:59
To call a python function from MATLAB and store the output of the python function in the MATLAB workspace, you may follow the below steps-
  1. Configure your system to use python. To do so, follow the steps mentioned in this MATLAB documentation link - https://www.mathworks.com/help/releases/R2024b/matlab/matlab_external/install-supported-python-implementation.html#bujjwjn
  2. Create the input array and list using the “py.list” class - https://www.mathworks.com/help/matlab/matlab_external/pythonlistvariables.html#:~:text=To%20call%20a%20Python%20function%20that%20takes%20a%20list%20input%20argument%2C%20create%20a%20py.list%20variable
  3. Load the python module and call the python function using the “py.importlib.import_module” function. For more information on importing python modules, refer to this link - https://www.mathworks.com/help/matlab/matlab_external/call-user-defined-custom-module.html
  4. The function will return the updated values as “py.list” objects which can then be converted to a MATLAB variable by calling the “cell” function. Refer to this link for more details about the “cell” function - https://www.mathworks.com/help/matlab/ref/cell.html#d126e195291:~:text=C%20%3D%20cell(n)%20returns%20an%20n%2Dby%2Dn%20cell%20array%20of%20empty%20matrices.
The results matrices and vectors can then be seen in the MATLAB workspace.
Hope this helps!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!