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

2 visualizaciones (últimos 30 días)

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.

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 2 de Abr. de 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))

Más respuestas (0)

Categorías

Más información sobre Call Python from MATLAB en Help Center y File Exchange.

Productos


Versión

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by