Issues in using matlab in python

조회 수: 4 (최근 30일)
Ajai Singh
Ajai Singh 2022년 8월 17일
답변: Abhijeet 2023년 9월 1일
Hello everyone ,
I am trying to solve an optimization problem where the input to the function to be optimized is a 12x1 vector and the output is a matrix of size 6x3.
I tried solving this using fsolve, root solvers from scipy.optimize
but got the following error:
fsolve: there is a mismatch between the input and output shape of the 'func' argument 'f'.Shape should be (12,) but it is (6,3).
but this problem can be easily solved in matlab using fsolve.
So i created a very simplified version of the original problem :
import matlab.engine
eng = matlab.engine.start_matlab()
import numpy as np
func = lambda x: x[0]**2 + x[1]**2 -25
eng.fsolve(func,eng.rand(2,1))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\reach\anaconda3\envs\MyEnv\lib\site-packages\matlab\engine\matlabengine.py", line 66, in __call__
out=_stdout, err=_stderr)
TypeError: unsupported Python data type: function
Any suggestion would be of great help.
Thank you.

답변 (1개)

Abhijeet
Abhijeet 2023년 9월 1일
Hi Ajai,
I can understand that you are facing issue while using ‘MATLAB Engine API for Python’. The error you're encountering is due to the fact that you're passing a Python lambda function (func) to the eng.fsolve function, which expects a MATLAB function handle.
I would suggest to code ‘func’ function in MATLAB script and then use that script in python script.
For more information on using MATLAB script in python, refer to the following documentation: -https://www.mathworks.com/help/matlab/matlab_external/call-user-script-and-function-from-python.html

카테고리

Help CenterFile Exchange에서 Call MATLAB from Python에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by