how can run a python function in matlab, with a matlab function inside the python function

6 次查看(过去 30 天)
For example, I have define a matlab function
f_mat(a,b)
, and a python function
f_py(f_mat',a',b')
It will run in matlab as:
py.f_py(f_mat',a',b')
Can I pass the matlab function f_mat(a,b) and parameters a,b directly to this python function? I guess not, inside the python function, all the function or parameters should be in python form. how to convert the matlab function that python can use?

回答(1 个)

Tejas
Tejas 2024-2-19
Hello Peng Wu,
Passing a MATLAB function as an argument to a Python function can be somewhat complex due to the different execution environments of MATLAB and Python. However, I have a practical workaround to propose. Begin by saving the MATLAB function that you wish to execute from the Python script into a separate file.
Once you have your MATLAB function in a standalone file, you can access it from your Python script using the 'MATLAB Engine API'. This API bridges the gap between the two languages, allowing your Python code to interact directly with the MATLAB file.
After setting up the API, encapsulate your Python code in a separate file. This organization will enable you to invoke the Python file from MATLAB using the pyrunfile function.
The example I have provided consists of three files: 'product.m', which is the MATLAB file to be called from the Python script; a Python file named 'python_func.py'; and a main MATLAB file named 'Main.m', from which the Python file will be executed. I have changed the structure of python file to only take two inputs : a & b.
Make sure that all these files are either located in the same directory or have been added to the MATLAB path. Below is the code for each file, along with a screenshot showing the output.
product.m
function num = product(a,b)
num = a * b ;
end
python_func.py
import matlab.engine
def python_function(a,b):
Engine = matlab.engine.start_matlab()
matlab_a = matlab.double([a])
matlab_b = matlab.double([b])
result = Engine.product(matlab_a,matlab_b)
Engine.quit()
return result
z=python_function(a,b)
Main.m
res= pyrunfile("python_func.py","z",a=3,b=5);
disp(res);
ScreenShot of Output
This solution is tested on MATLAB R2023b and Python 3.11.8 .
Hope it helps!

类别

Help CenterFile Exchange 中查找有关 Call MATLAB from Python 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by