Default Numeric Types in MATLAB and Python - MATLAB & Simulink (original) (raw)
Main Content
By default, a number in MATLAB® has a double-precision type. However, in Python®, a number without a fractional part has, by default, an integer type. As a result of this difference, when calling MATLAB from Python using the MATLAB Engine API for Python, if you pass a Python variable as an input argument to a MATLAB function that expects a double-precision number, you might need to convert the data type of the variable first.
If instead you want to pass data to a Python function from within MATLAB, see Use Python Numeric Variables in MATLAB for more information.
Consider these variable assignments in MATLAB.
Both x
and y
are of the data typedouble
. You can verify their data types using the isfloat function.
fprintf("x is a float: %s\ny is a float: %s",string(isfloat(x)),string(isfloat(y)))
x is a float: true y is a float: true
Now consider the same assignments in Python.
x
and y
are of different numeric data types. View the data type of x
using print
andtype
.
Now view the data type of y
.
Most MATLAB functions take numeric input arguments of data typedouble
. The best practice is to ensure that numbers you pass as input arguments to MATLAB functions are of Python data type float
, not Python data type int
. You can ensure that Python variables are floating-point numbers if you:
- Change literals to floating-point numbers. For example, type
4.0
instead of4
. - Convert numbers to data type
float
. For example,x = float(4)
casts the number to data typefloat
. - Create a
matlab.double
array from a number or sequence. For example,x = matlab.double([1,2,3,4,5])
creates an array of MATLAB data typedouble
from alist
of Python integers.
When you pass an integer to a MATLAB function that takes an input argument of data typedouble
, the MATLAB Engine API for Python returns an error. See MatlabExecutionError: Undefined Function for an example.
When you call a MATLAB function that does take integers as numeric input arguments, you can pass input arguments of Python data type int
to the function.