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

2 views (last 30 days)

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.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 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))

More Answers (0)

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!