Hi @Tik Ho HUI,
After going through documentation provided at the link below,
https://www.mathworks.com/help/matlab/matlab_external/call-user-script-and-function-from-python.html
& to help you achieve the goal of passing parameters from Python to MATLAB and retrieving results, you can follow these steps:
Set Up the MATLAB Function: You need to modify your MATLAB script (Python_testing.m) into a function that accepts parameters. Here’s how you can structure it:
function a = Python_testing(x, y, z) % Calculate the average of x, y, and z a = 0.5 * (x + y + z); return; % Not strictly necessary as it's implicit end
Modify the Python Code: In your Python code, you need to pass the variables x,y and z when calling the Python_testing function. Here is how your modified Python code should look:
import matlab.engine
# Start the MATLAB engine eng = matlab.engine.start_matlab()
# Define your variables x = 0 y = 1 z = 2
# Call the MATLAB function with parameters result = eng.Python_testing(x, y, z)
# Print the result returned from MATLAB print(result) # This will print the value of 'a'
You have to understand that in MATLAB, functions are defined using the function keyword followed by the output variable and the function name. This allows you to accept input parameters directly. So, when you call eng.Python_testing(x, y, z), you are sending the values of x,y and z from Python to MATLAB. The MATLAB Engine API handles type conversion automatically (e.g., Python integers are converted to MATLAB doubles). Also, the value computed in MATLAB a is returned to Python when you call it with result = eng.Python_testing(x, y, z). You can then use this value in your Python script.
Make sure that your .m file (e.g., Python_testing.m) is located in a directory that is on the MATLAB path. If not, you can add it using:
eng.addpath(r'C:\path\to\your\matlab\files', nargout=0)
By following these guidelines, you should be able to successfully pass parameters from your Python program to your MATLAB script and retrieve results effectively.
If you encounter specific errors during implementation, feel free to ask for further assistance!