Skill Tracer
Skills › Scientific Agent Skills › matlab › python-integration.md

python-integration.md

264 lines · skills/matlab/references/python-integration.md at 5f2bc03

Open on GitHub

Most marks come from matching words in the file, so treat them as pointers.

1# MATLAB and Python Integration
2
3The executable planner is pinned to MATLAB R2026a, reviewed on 2026-10-01.
4Calling Python from MATLAB and calling MATLAB from Python are different
5interfaces with different process, data, and license behavior.
6
7Current R2026b documentation lists CPython 3.10-3.14. At review time, PyPI
8still publishes `matlabengine==26.1.12` for R2026a, not R2026b. For R2026b use
9the Engine distributed with that installed release and verify its requirements;
10the bundled planner deliberately rejects R2026b rather than applying the
11R2026a package pin. No MATLAB or Engine runtime was started in this review.

MATLAB and Python Integration

The executable planner is pinned to MATLAB R2026a, reviewed on 2026-10-01. Calling Python from MATLAB and calling MATLAB from Python are different interfaces with different process, data, and license behavior.

Current R2026b documentation lists CPython 3.10-3.14. At review time, PyPI still publishes matlabengine==26.1.12 for R2026a, not R2026b. For R2026b use the Engine distributed with that installed release and verify its requirements; the bundled planner deliberately rejects R2026b rather than applying the R2026a package pin. No MATLAB or Engine runtime was started in this review.

Raw lines 1 to 12
13## Exact R2026a compatibility
15MathWorks' support table lists 64-bit CPython **3.9, 3.10, 3.11, 3.12,
16and 3.13** for:
18- MATLAB Interface to Python;
19- MATLAB Engine for Python;
20- MATLAB Compiler SDK for Python;
21- MATLAB Production Server Client Library.
23The current MathWorks-maintained PyPI release reviewed here is
24`matlabengine==26.1.12`, released 2026-05-08. It requires MATLAB R2026a.
25Do not install a floating latest package for a reproducible environment.
27```bash
28uv pip install "matlabengine==26.1.12"
29```
31Installation does not include MATLAB or grant a license. Engine requires an
32installed R2026a on the same machine; MATLAB Runtime alone is insufficient.
33The Python architecture must match MATLAB.
35R2026a also ships a preinstalled Engine distribution at the single named path:
37```text
38<matlabroot>/extern/engines/python/dist
39```
41Add only that confirmed path to the selected environment when using this
42method. Do not print or upload the full `PATH`, `PYTHONPATH`, environment,
43license configuration, home directory, or credentials.

Exact R2026a compatibility

MathWorks' support table lists 64-bit CPython 3.9, 3.10, 3.11, 3.12, and 3.13 for:

  • MATLAB Interface to Python;
  • MATLAB Engine for Python;
  • MATLAB Compiler SDK for Python;
  • MATLAB Production Server Client Library.

The current MathWorks-maintained PyPI release reviewed here is matlabengine==26.1.12, released 2026-05-08. It requires MATLAB R2026a. Do not install a floating latest package for a reproducible environment.

uv pip install "matlabengine==26.1.12"

Installation does not include MATLAB or grant a license. Engine requires an installed R2026a on the same machine; MATLAB Runtime alone is insufficient. The Python architecture must match MATLAB.

R2026a also ships a preinstalled Engine distribution at the single named path:

<matlabroot>/extern/engines/python/dist

Add only that confirmed path to the selected environment when using this method. Do not print or upload the full PATH, PYTHONPATH, environment, license configuration, home directory, or credentials.

Raw lines 13 to 44
45## Plan compatibility without execution
47```bash
48python scripts/plan_python_compatibility.py \
49 --matlab-release R2026a \
50 --python-version 3.13 \
51 --engine-version 26.1.12
52```
54The planner uses a bundled dated support table. It does not import
55`matlab.engine`, inspect the environment, locate installations, start MATLAB,
56or check out a license. `--include-launch-snippet` adds an explicitly labeled
57launch example to the JSON plan but still does not execute it.

Plan compatibility without execution

python scripts/plan_python_compatibility.py \
  --matlab-release R2026a \
  --python-version 3.13 \
  --engine-version 26.1.12

The planner uses a bundled dated support table. It does not import matlab.engine, inspect the environment, locate installations, start MATLAB, or check out a license. --include-launch-snippet adds an explicitly labeled launch example to the JSON plan but still does not execute it.

Raw lines 45 to 58
Runs code python scripts/plan_python_compatibility.py :48
59## Calling Python from MATLAB
61Review and pin one interpreter before any `py.*` access:
63```matlab
64environment = pyenv( ...
65 Version="/reviewed/venv/bin/python", ...
66 ExecutionMode="OutOfProcess");
67```
69On Windows, a registered version can be selected by version, but a full named
70executable is clearer. On macOS/Linux, use the full executable. The Python
71build architecture must match MATLAB. MATLAB does not support CPython from the
72Microsoft Store.
74Interpreter switching:
76- in-process: restart MATLAB before changing the loaded interpreter;
77- out-of-process: `terminate(pyenv)` can stop the external interpreter, after
78 which `pyenv` can be reconfigured.
80Out-of-process isolates interpreter crashes and allows reload, but it is not a
81security sandbox. Data plus transfer metadata are limited to 2 GiB per
82out-of-process transfer. Python modules can perform arbitrary process, file,
83network, native, and credential operations.
85Never run untrusted `py.*`, `pyrun`, `pyrunfile`, Python modules, wheels, or
86requirements files. `pyrun` and `pyrunfile` are dynamic code execution
87surfaces.

Calling Python from MATLAB

Review and pin one interpreter before any py.* access:

environment = pyenv( ...
    Version="/reviewed/venv/bin/python", ...
    ExecutionMode="OutOfProcess");

On Windows, a registered version can be selected by version, but a full named executable is clearer. On macOS/Linux, use the full executable. The Python build architecture must match MATLAB. MATLAB does not support CPython from the Microsoft Store.

Interpreter switching:

  • in-process: restart MATLAB before changing the loaded interpreter;
  • out-of-process: terminate(pyenv) can stop the external interpreter, after which pyenv can be reconfigured.

Out-of-process isolates interpreter crashes and allows reload, but it is not a security sandbox. Data plus transfer metadata are limited to 2 GiB per out-of-process transfer. Python modules can perform arbitrary process, file, network, native, and credential operations.

Never run untrusted py.*, pyrun, pyrunfile, Python modules, wheels, or requirements files. pyrun and pyrunfile are dynamic code execution surfaces.

Raw lines 59 to 88
Runs code bin/python :65
89## Calling MATLAB from Python
91Starting Engine is explicit execution:
93```python
94import matlab.engine
96engine = matlab.engine.start_matlab()
97try:
98 result = engine.sqrt(16.0)
99finally:
100 engine.quit()
101```
103`start_matlab()` creates a MATLAB process, can execute startup code, and can
104check out a MATLAB license. Never call it merely to probe availability.
105Review startup paths/actions and confirm entitlement first.
107Engine transfers are limited to 2 GB including supporting information.
108Python `None`, Python class objects, and recursive containers are unsupported
109Engine input types. These limits are separate from MATLAB-to-Python conversion.
111`connect_matlab()` connects to a deliberately shared local MATLAB session;
112`find_matlab()` lists shared sessions. Sharing changes the trust boundary and
113must be explicitly approved. Do not connect to an unknown session.
115Only add narrow reviewed paths:
117```python
118engine.addpath("/reviewed/project/src", nargout=0)
119value = engine.analyzeSignal(
120 matlab.double([[1.0], [2.0], [3.0]]),
121 nargout=1,
123```
125Do not use recursive path additions. Pass fixed function names, not text to
126`eval`, and set `nargout` deliberately. Redirect output to bounded
127`io.StringIO` only when needed; logs can contain paths or data.

Calling MATLAB from Python

Starting Engine is explicit execution:

import matlab.engine

engine = matlab.engine.start_matlab()
try:
    result = engine.sqrt(16.0)
finally:
    engine.quit()

start_matlab() creates a MATLAB process, can execute startup code, and can check out a MATLAB license. Never call it merely to probe availability. Review startup paths/actions and confirm entitlement first.

Engine transfers are limited to 2 GB including supporting information. Python None, Python class objects, and recursive containers are unsupported Engine input types. These limits are separate from MATLAB-to-Python conversion.

connect_matlab() connects to a deliberately shared local MATLAB session; find_matlab() lists shared sessions. Sharing changes the trust boundary and must be explicitly approved. Do not connect to an unknown session.

Only add narrow reviewed paths:

engine.addpath("/reviewed/project/src", nargout=0)
value = engine.analyzeSignal(
    matlab.double([[1.0], [2.0], [3.0]]),
    nargout=1,
)

Do not use recursive path additions. Pass fixed function names, not text to eval, and set nargout deliberately. Redirect output to bounded io.StringIO only when needed; logs can contain paths or data.

Raw lines 89 to 128
129## MATLAB-to-Python conversion in R2026a
131Scalar automatic mappings include:
133| MATLAB | Python |
134|---|---|
135| real `double`/`single` | `float` by default; type hints can select `int` |
136| complex float | `complex` |
137| integer scalar | `int` |
138| logical scalar | `bool` |
139| string scalar/character vector | `str` |
140| missing string through `py.str` | Python string `"None"`, not the Python `None` singleton |
141| `dictionary`/scalar `struct` | `dict` |
142| `table`/`timetable` | pandas `DataFrame` |
143| `datetime` | `datetime.datetime` |
144| `duration` | `datetime.timedelta` |
146With NumPy available, numeric/logical MATLAB arrays convert to NumPy arrays
147with corresponding precision/sign/complex dtype. Without NumPy, numeric arrays
148use Python buffer/memoryview behavior. Since R2025a, array conversion behavior
149changed; test code migrated from older vector `array.array` assumptions.
151R2026a additions:
153- MATLAB string vectors automatically convert to Python lists;
154- `pystringarray` converts MATLAB string arrays to NumPy `StringDType`
155 arrays;
156- missing string entries need explicit round-trip tests.
158The table above concerns Python called **from MATLAB**. Engine calls from
159Python use their own conversion table and `matlab.*` array classes; do not
160assume pandas, datetime, or dictionary conversions are symmetric. R2026b adds
161GPU interchange through CuPy, DLPack, and PyTorch with Parallel Computing
162Toolbox; those features are outside the R2026a planner's compatibility claim.
164No automatic conversion is documented for multidimensional character/cell
165arrays or M-by-N string arrays where both dimensions exceed one. Sparse
166arrays, nonscalar structure arrays, categorical arrays, `containers.Map`,
167MATLAB objects, and metadata classes are unsupported in the MATLAB-to-Python
168interface.

MATLAB-to-Python conversion in R2026a

Scalar automatic mappings include:

MATLABPython
real double/singlefloat by default; type hints can select int
complex floatcomplex
integer scalarint
logical scalarbool
string scalar/character vectorstr
missing string through py.strPython string "None", not the Python None singleton
dictionary/scalar structdict
table/timetablepandas DataFrame
datetimedatetime.datetime
durationdatetime.timedelta

With NumPy available, numeric/logical MATLAB arrays convert to NumPy arrays with corresponding precision/sign/complex dtype. Without NumPy, numeric arrays use Python buffer/memoryview behavior. Since R2025a, array conversion behavior changed; test code migrated from older vector array.array assumptions.

R2026a additions:

  • MATLAB string vectors automatically convert to Python lists;
  • pystringarray converts MATLAB string arrays to NumPy StringDType arrays;
  • missing string entries need explicit round-trip tests.

The table above concerns Python called from MATLAB. Engine calls from Python use their own conversion table and matlab.* array classes; do not assume pandas, datetime, or dictionary conversions are symmetric. R2026b adds GPU interchange through CuPy, DLPack, and PyTorch with Parallel Computing Toolbox; those features are outside the R2026a planner's compatibility claim.

No automatic conversion is documented for multidimensional character/cell arrays or M-by-N string arrays where both dimensions exceed one. Sparse arrays, nonscalar structure arrays, categorical arrays, containers.Map, MATLAB objects, and metadata classes are unsupported in the MATLAB-to-Python interface.

Raw lines 129 to 169
170## Python-to-MATLAB conversion
172MATLAB automatically converts selected scalar Python returns. Other values use
173explicit conversion:
175| Python value | MATLAB conversion |
176|---|---|
177| `py.str` | `string` or `char` |
178| Python numeric scalar | `double`, `single`, or integer constructors |
179| `py.bytes` | `uint8` |
180| `py.numpy.ndarray` | matching MATLAB numeric class or `string` where supported |
181| `py.list`/`py.tuple` | numeric/logical/string/cell conversion when homogeneous/compatible |
182| mapping protocol / `py.dict` | `dictionary` or `struct` |
183| pandas `DataFrame` | `table`/`timetable` with documented conversion |
184| Python datetime/timedelta/NumPy time | MATLAB `datetime`/`duration` conversions |
186Always test:
188- rank and row/column orientation;
189- C-order versus column-major interpretation;
190- dtype width/sign and complex values;
191- `NaN`, `Inf`, `None`, `NaT`, missing strings, and categorical values;
192- table index versus timetable row times;
193- time zones and units;
194- dictionary key restrictions and column-name normalization;
195- copies versus shared/buffer-backed memory.
197Do not flatten an array to "fix" a shape mismatch without recording the
198ordering contract.

Python-to-MATLAB conversion

MATLAB automatically converts selected scalar Python returns. Other values use explicit conversion:

Python valueMATLAB conversion
py.strstring or char
Python numeric scalardouble, single, or integer constructors
py.bytesuint8
py.numpy.ndarraymatching MATLAB numeric class or string where supported
py.list/py.tuplenumeric/logical/string/cell conversion when homogeneous/compatible
mapping protocol / py.dictdictionary or struct
pandas DataFrametable/timetable with documented conversion
Python datetime/timedelta/NumPy timeMATLAB datetime/duration conversions

Always test:

  • rank and row/column orientation;
  • C-order versus column-major interpretation;
  • dtype width/sign and complex values;
  • NaN, Inf, None, NaT, missing strings, and categorical values;
  • table index versus timetable row times;
  • time zones and units;
  • dictionary key restrictions and column-name normalization;
  • copies versus shared/buffer-backed memory.

Do not flatten an array to "fix" a shape mismatch without recording the ordering contract.

Raw lines 170 to 199
200## MATLAB Engine array classes
202The `matlab` Python package provides MATLAB array classes such as
203`matlab.double`, `matlab.single`, signed/unsigned integer classes, and
204`matlab.logical`. These are for Engine calls, not general NumPy replacements.
206```python
207column = matlab.double([[1.0], [2.0], [3.0]])
208matrix = matlab.double([[1.0, 2.0], [3.0, 4.0]])
209```
211Construct the intended dimensions explicitly. Function outputs can be Engine
212proxy/object types; convert only through documented APIs.

MATLAB Engine array classes

The matlab Python package provides MATLAB array classes such as matlab.double, matlab.single, signed/unsigned integer classes, and matlab.logical. These are for Engine calls, not general NumPy replacements.

column = matlab.double([[1.0], [2.0], [3.0]])
matrix = matlab.double([[1.0, 2.0], [3.0, 4.0]])

Construct the intended dimensions explicitly. Function outputs can be Engine proxy/object types; convert only through documented APIs.

Raw lines 200 to 213
214## Serialization and exchange
216- MATLAB does not support saving Python objects into MAT files.
217- Never use Python pickle for MATLAB exchange. Pickle deserialization executes
218 attacker-controlled behavior.
219- For simple data, prefer schema-documented CSV/JSON/Parquet/HDF5.
220- For trusted MATLAB arrays, use MAT with explicit version and inventory it
221 before loading in another process.
222- SciPy `loadmat` is not used by this skill's inventory. It can deserialize
223 complex structures and is not a safety scanner.

Serialization and exchange

  • MATLAB does not support saving Python objects into MAT files.
  • Never use Python pickle for MATLAB exchange. Pickle deserialization executes attacker-controlled behavior.
  • For simple data, prefer schema-documented CSV/JSON/Parquet/HDF5.
  • For trusted MATLAB arrays, use MAT with explicit version and inventory it before loading in another process.
  • SciPy loadmat is not used by this skill's inventory. It can deserialize complex structures and is not a safety scanner.
Raw lines 214 to 224
225## Compiler SDK distinction
227MATLAB Compiler SDK for Python packages are not MATLAB Engine:
229- building requires MATLAB, MATLAB Compiler SDK, and source dependencies;
230- deployed components use a compatible MATLAB Runtime under applicable terms;
231- generated Python packages are not supported as Python modules called back
232 from MATLAB's Python interface;
233- Engine itself requires full installed MATLAB, not Runtime.
235Confirm product, target release, platform, package, runtime, and license terms.

Compiler SDK distinction

MATLAB Compiler SDK for Python packages are not MATLAB Engine:

  • building requires MATLAB, MATLAB Compiler SDK, and source dependencies;
  • deployed components use a compatible MATLAB Runtime under applicable terms;
  • generated Python packages are not supported as Python modules called back from MATLAB's Python interface;
  • Engine itself requires full installed MATLAB, not Runtime.

Confirm product, target release, platform, package, runtime, and license terms.

Raw lines 225 to 236
237## Troubleshooting without broad disclosure
239Collect only named facts:
241- MATLAB release/update and architecture;
242- one Python executable path and `major.minor`;
243- Engine package version;
244- selected `pyenv` status/mode (not all environment values);
245- one failing function, input classes/shapes, and redacted traceback;
246- whether NumPy/pandas are required and their pinned versions.
248Do not ask for `env`, `set`, complete `PATH`, complete `sys.path`, license
249files, tokens, home-directory listings, or credentials.

Troubleshooting without broad disclosure

Collect only named facts:

  • MATLAB release/update and architecture;
  • one Python executable path and major.minor;
  • Engine package version;
  • selected pyenv status/mode (not all environment values);
  • one failing function, input classes/shapes, and redacted traceback;
  • whether NumPy/pandas are required and their pinned versions.

Do not ask for env, set, complete PATH, complete sys.path, license files, tokens, home-directory listings, or credentials.

Raw lines 237 to 250
251## Sources (reviewed 2026-10-01)
253- [Python Compatibility by MATLAB Release](https://www.mathworks.com/support/requirements/python-compatibility.html)
254- [Install MATLAB Engine API for Python](https://www.mathworks.com/help/matlab/matlab_external/install-the-matlab-engine-for-python.html)
255- [MathWorks `matlabengine` 26.1.12 package](https://pypi.org/project/matlabengine/26.1.12/)
256- [Call MATLAB from Python](https://www.mathworks.com/help/matlab/matlab-engine-for-python.html)
257- [Get Started with MATLAB Engine](https://www.mathworks.com/help/matlab/matlab_external/get-started-with-matlab-engine-for-python.html)
258- [Configure Python for MATLAB](https://www.mathworks.com/help/matlab/matlab_external/install-supported-python-implementation.html)
259- [Call Python from MATLAB](https://www.mathworks.com/help/matlab/call-python-libraries.html)
260- [Pass Data from MATLAB to Python](https://www.mathworks.com/help/matlab/matlab_external/passing-data-to-python.html)
261- [Pass Data from Python to MATLAB](https://www.mathworks.com/help/matlab/matlab_external/pass-data-between-matlab-and-python-from-python.html)
262- [Python Interface Limitations](https://www.mathworks.com/help/matlab/matlab_external/limitations-to-python-support.html)
263- [MATLAB Engine Limitations](https://www.mathworks.com/help/matlab/matlab_external/limitations-to-the-matlab-engine-for-python.html)
264- [Current release highlights](https://www.mathworks.com/products/new_products/latest_features.html)