Why is an integer input of a Python function that is run in MATLAB R2023b not being read correctly?

2 Ansichten (letzte 30 Tage)

I have a Python function from a module that runs successfully from the terminal or another IDE. I am trying to run the function in MATLAB by importing the module, and then calling the function using MATLAB's Python interface. There are no issues with the Python environment in MATLAB, or with loading the module using "py.importlib.import_module". However, when running the function in MATLAB, the integer input of the function is not being read correctly and this is leading to the function not behaving as expected.

Akzeptierte Antwort

MathWorks Support Team
MathWorks Support Team am 2 Apr. 2024
This may be caused by the fact that MATLAB stores all numeric values as doubles by default. So if you have a Python function "foo" in module "mymod" that takes an integer, then running "py.mymod.foo(5)" in MATLAB actually runs "py.mymod.foo(5.0)". This can cause issues if the Python function requires an integer value.
In order to get around this, you need to explicitly cast the number input as an integer before passing it into the Python function. You can do this using the int32 function, like so.
py.mymod.foo(int32(5))

Weitere Antworten (0)

Kategorien

Mehr zu Call Python from MATLAB finden Sie in Help Center und File Exchange

Produkte


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by