MATLAB Data Types Supported by the `matlab_to_python` Conversion Function
The matlab_to_python function in jigarbhoye04/matlabmcp actively converts only matlab.double, matlab.logical, and matlab.char into native Python objects, while all other MATLAB types fall back to string representation or error placeholders.
The matlabmcp repository bridges MATLAB and Python using the MATLAB Engine API. Understanding which MATLAB data types the matlab_to_python conversion function handles is essential for building reliable data pipelines. This analysis examines the implementation in main.py to identify exactly which types become JSON-serializable Python objects and which require manual intervention.
Supported MATLAB Data Types
The conversion logic resides in main.py between lines 53 and 77. It explicitly handles four data categories through cascading isinstance checks, ensuring JSON-compatible outputs.
Numeric Arrays (matlab.double)
At line 59, the function detects matlab.double instances using isinstance(data, matlab.double). The conversion wraps the value in a NumPy array, applies squeeze() to remove singleton dimensions, and then:
- Returns a Python
floatif the result is a scalar - Returns a nested Python
listof numbers for multidimensional arrays
Boolean Arrays (matlab.logical)
Line 63 checks for matlab.logical types using isinstance(data, matlab.logical). The processing mirrors numeric arrays:
- Scalar values become Python
boolobjects - Arrays convert to nested
liststructures containingTrueorFalsevalues
Character Arrays (matlab.char)
Detected at line 67 via isinstance(data, matlab.char), MATLAB character arrays convert directly to Python strings using str(data). This handles string literals and row vectors from the MATLAB workspace.
Python Native Primitives
Line 57 passes through existing Python primitives—including str, int, float, bool, and None—unchanged. This ensures idempotent behavior when data originates from Python contexts or has already been converted.
Unsupported MATLAB Types and Fallback Behavior
Any MATLAB type not explicitly handled above—including structs, cell arrays, tables, sparse matrices, function handles, and MATLAB objects—falls into the else block at line 70.
For these unsupported types, the function:
- Logs a warning message indicating the type is unserializable
- Attempts conversion via
str(data) - Returns a descriptive placeholder string
"Unserializable MATLAB Type: <type>"if stringification fails
This fallback preserves runtime stability but loses structural data, potentially breaking JSON serialization for complex objects that require nested dictionaries or lists.
Implementation Details in main.py
The matlab_to_python function uses a defensive type-checking pattern to handle MATLAB Engine return values:
def matlab_to_python(data):
if isinstance(data, (str, int, float, bool, type(None))):
return data
elif isinstance(data, matlab.double):
# NumPy conversion, squeeze, scalar check
arr = np.array(data)
arr = np.squeeze(arr)
if arr.ndim == 0:
return float(arr)
return arr.tolist()
elif isinstance(data, matlab.logical):
# Similar logic yielding bool for scalars
elif isinstance(data, matlab.char):
return str(data)
else:
# Warning and string fallback (line 70)
logging.warning(f"Unserializable MATLAB Type: {type(data)}")
try:
return str(data)
except:
return f"Unserializable MATLAB Type: {type(data)}"
This structure prioritizes common numerical and text data while providing a safe fallback for MATLAB-specific complex objects.
Practical Conversion Examples
Converting MATLAB Double Matrices
import matlab.engine
from main import matlab_to_python
eng = matlab.engine.start_matlab()
matlab_mat = eng.eval('reshape(1:6, 2, 3)', nargout=1)
py_val = matlab_to_python(matlab_mat)
print(py_val)
# Output: [[1.0, 3.0, 5.0], [2.0, 4.0, 6.0]]
Handling Logical Scalars
log = eng.eval('true', nargout=1)
result = matlab_to_python(log)
print(result, type(result))
# Output: True <class 'bool'>
Character Array Conversion
txt = eng.eval("'Hello MATLAB'", nargout=1)
print(matlab_to_python(txt))
# Output: Hello MATLAB
Unsupported Struct Types
eng.eval("s = struct('a', 1, 'b', 2);", nargout=0)
struct_val = eng.workspace['s']
print(matlab_to_python(struct_val))
# Output: "Unserializable MATLAB Type: <class 'matlab.engine.matlabobject'>"
Summary
- Actively supported:
matlab.double(converts tofloator nestedlist),matlab.logical(converts toboolor nestedlist), andmatlab.char(converts tostr) - Pass-through types: Python primitives (
str,int,float,bool,None) returned unchanged at line 57 ofmain.py - Unsupported types: Structs, cell arrays, tables, sparse matrices, and MATLAB objects fall back to string representation via the
elseblock at line 70 - Critical limitation: Only three MATLAB native types receive structured conversion; complex data structures require manual preprocessing before calling
matlab_to_python
Frequently Asked Questions
Does matlab_to_python support MATLAB tables and timetables?
No. According to the source code in main.py, MATLAB tables and timetables are not explicitly handled. They fall into the else block at line 70 and return a string representation or "Unserializable MATLAB Type" placeholder, effectively losing the tabular structure and column metadata required for DataFrame conversion.
How does the function handle multidimensional MATLAB arrays?
The function converts multidimensional matlab.double and matlab.logical arrays by first wrapping them in NumPy arrays, squeezing singleton dimensions with np.squeeze(), then converting to nested Python lists using .tolist(). This preserves numerical values but represents the data as standard Python lists rather than preserving MATLAB's matrix structure.
Can I modify matlab_to_python to support MATLAB structs?
Yes. The current implementation uses explicit type checking at lines 59, 63, and 67. You would need to add an elif isinstance(data, matlab.struct) branch before the final else block at line 70 to recursively convert struct fields into Python dictionaries. Without this modification, structs only receive string representation, making their field data inaccessible programmatically.
What happens to complex numbers from MATLAB?
Complex numbers are not explicitly handled in the type checks. If MATLAB returns a complex value as matlab.double, the NumPy conversion may preserve the complex dtype, but scalar conversion to float will raise a TypeError. The function lacks specific handling for complex numbers, meaning they may either cast incorrectly or fall back to the string representation depending on the NumPy array state.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →