Default Numeric Types in MATLAB and Python
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.
x = 4; y = 4.0;
Both x and y are of the data type
double. 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 = 4 y = 4.0
x and y are of different numeric data types.
View the data type of x using print and
type.
print(type(x))
<type 'int'>
Now view the data type of y.
print(type(y))
<type 'float'>
Most MATLAB functions take numeric input arguments of data type
double. 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.0instead of4.Convert numbers to data type
float. For example,x = float(4)casts the number to data typefloat.Create a
matlab.doublearray from a number or sequence. For example,x = matlab.double([1,2,3,4,5])creates an array of MATLAB data typedoublefrom alistof Python integers.
When you pass an integer to a MATLAB function that takes an input argument of data type
double, 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.