Python Code Block Reference
Library path: simulink/User-Defined Functions/Python Code (R2025a+)
The Python Code block is the way to run Python inside a Simulink model. When
a user asks to run a Python function, call a Python class, or use a Python
library each timestep, this block is the tool — they may not name it explicitly.
Use it even when a MATLAB Function block or MATLAB System object calling py.*
(coder.extrinsic) would produce the same numbers: those cannot build in Rapid
Accelerator or model reference Accelerator mode, and they hide the Python behind
a MATLAB block. The Python Code block works in both modes.
It converts inputs to Python objects, builds a dict keyed by symbol name, calls
exec() with that dict as namespace, then converts outputs back to Simulink
types. The interpreter is shared with MATLAB py.* — same process, modules, and
state.
- Environment setup — pyenv, venvs, sys.path, module reloading
- Examples — verified programmatic patterns
- PythonObject patterns — class integration and persistent state
When to Use
- Running a line or block of Python each timestep inside a Simulink model
- Calling a Python function, class, or third-party library (numpy, scipy, …) from a model
- Persisting a Python object or numeric state across timesteps
- Passing a tunable parameter or a vector/matrix signal into Python
- The user describes the goal ("run my Python code in the model") without naming the block
When NOT to Use
- Pure MATLAB-side Python calls with no model involved — use
py.* directly, no block needed
- MATLAB Function blocks or S-Functions — those are different mechanisms
- Running a pretrained deep-learning model (PyTorch/TensorFlow/ONNX) — use the Deep Learning Toolbox Model Predict blocks (PyTorch/TensorFlow/ONNX/Custom Python Model Predict), which run via Python co-execution and are configured through the block's model-file tabs, not
SymbolSpec
- General Simulink model construction unrelated to Python — use the
building-simulink-models skill
Workflow
Build the block in this order — ports do not exist until symbols are
defined, so wiring comes last. The build takes five tool calls; batch the
operations in each call:
- Create and save the model (
evaluate_matlab_code) — model_edit needs
an existing model file.
- Add and configure all blocks — one
model_edit call. Put the code
parameters (OutputCode, InitializeConditionsCode, TerminateCode,
SampleTime) in add_block params. The Python Code block is created with
no ports. The response maps each ref to its blk_N ID:[{"op":"add_block","type":"simulink/Sources/Constant","ref":"src","params":{"Value":"3"}},{"op":"add_block","type":"simulink/User-Defined Functions/Python Code","ref":"py","name":"Py","params":{"OutputCode":"y = u * 2.0","SampleTime":"1"}},{"op":"add_block","type":"simulink/Sinks/Out1","ref":"out"}]
- Define symbols — one
evaluate_matlab_code call; this creates the ports.
SymbolSpec is a read-only handle reached only through
get_param(blk,'SymbolSpec'), and model_edit cannot configure symbols —
this is the one step that uses get_param directly. Call ss.addSymbol(...)
and set each symbol's Scope/Type/Size in place.
- Wire — one
model_edit call using the returned IDs:
[{"op":"connect","target":"blk_1.y1 -> blk_2.u1"},{"op":"connect","target":"blk_2.y1 -> blk_3.u1"}]
- Simulate and read the result — one
evaluate_matlab_code call. The
simulation compiles the block, so it is the verification; skip separate
inspection calls unless it fails.
The examples give the symbol definitions and code
parameters for common patterns; read them only when the pattern isn't covered
here.
To run the model programmatically and inspect results (sim/parsim,
Simulink.SimulationInput, logsout), use the simulating-simulink-models skill.
Block Parameters
| Parameter |
Type |
Notes |
InitializeConditionsCode |
string |
Runs once at simulation start |
OutputCode |
string |
Runs each timestep |
TerminateCode |
string |
Runs once at simulation end |
SampleTime |
string |
Default "-1" (inherited) |
SymbolSpec |
handle |
Read-only param — get and mutate in place, never set_param back |
What survives from InitializeConditionsCode to OutputCode: only imported
modules (import m, import m as x, import pkg.sub) and Persistent symbols.
Everything else in the init namespace is discarded — from m import f bindings,
functions, classes, and plain variables (k = 3) raise NameError in
OutputCode. Use the module-qualified form (import m → m.f(...)), repeat
the from import in OutputCode, or store objects in a Persistent symbol.
SymbolSpec API
Class: Simulink.PythonFunctionBlock.SymbolSpec (handle object).
ss = get_param(blk, 'SymbolSpec');
sym = ss.addSymbol('name'); % Returns Symbol — then set properties
sym.Scope = 'Input';
sym.Type = 'double';
sym.Size = '1';
got = ss.getSymbol('name'); % Retrieve existing
ss.deleteSymbol('name'); % Remove
Handle object: mutations apply immediately to the block.
Symbol Properties
| Property |
Values |
Notes |
Name |
char |
Variable name in Python namespace |
Scope |
'Input' 'Output' 'Parameter' 'Persistent' |
|
Type |
'double' 'single' 'int8' 'int16' 'int32' 'int64' 'uint8' 'uint16' 'uint32' 'uint64' 'boolean' 'string' 'Bus: <BusObject>' 'fixedpoint' 'PythonObject' |
PythonObject only for Persistent. Use lowercase 'boolean' — 'Boolean' is accepted by the setter but fails at compile ("not in scope"). A bus symbol names a Simulink.Bus object in the base workspace |
Size |
char |
'1', '3', '[2 3]', '-1' (inherit) |
Label |
char |
Port/mask display name |
PortNumber |
int |
Port ordering |
Data Type Mapping
| Simulink |
Python |
| scalar double |
float |
| vector/matrix double |
numpy.ndarray if numpy is available, else array.array. Shape follows Size ('[2 3]' ↔ (2, 3)); element (i,j) in MATLAB is [i-1, j-1] in Python — no transpose |
string |
str (output str becomes a MATLAB string). A root Inport fed from the workspace needs Interpolate off |
| bus (input) |
dict keyed by element name — u["a"] |
| scalar integer |
int |
| vector integer |
numpy.ndarray if numpy is available, else array.array |
PythonObject (Persistent) |
any Python object |
Limitations
- No variable-size signals or array of buses
- No continuous sample time with persistent variables
- No Dataflow Subsystems
- No rapid accelerator in For Each Subsystems
- No backward stepping with persistent variables
- Code generation supported (Python C API) — requires dev headers + interpreter linkage
Copyright 2026 The MathWorks, Inc.
1---2name: simulink-integrate-python-code3description: |4 Use this skill when running or integrating general Python code (functions,5 classes, libraries) inside a Simulink model with the Python Code block6 (R2025a+). Not for trained neural-network models (.pt, .onnx, .h5) or7 deep-learning inference; use the Deep Learning Toolbox Model Predict blocks8 or network importers. Covers the SymbolSpec API, data-type mapping,9 persistent state, shared interpreter, venvs, and module reloading.10 Triggers: "Python Code block", "Python in Simulink", "integrate Python",11 "call Python from Simulink", "run my Python function/class in a model",12 "add Python to model", "use a Python library in a simulation".13license: https://www.mathworks.com/content/dam/mathworks/license/pmrl/license.md14metadata:15 source: https://skillmd.com/skills/matlab/simulink-integrate-python-code16 author: MathWorks17 version: "1.0"18---1920# Python Code Block Reference2122Library path: `simulink/User-Defined Functions/Python Code` (R2025a+)2324The **Python Code block** is the way to run Python inside a Simulink model. When25a user asks to run a Python function, call a Python class, or use a Python26library each timestep, this block is the tool — they may not name it explicitly.2728Use it even when a MATLAB Function block or MATLAB System object calling `py.*`29(`coder.extrinsic`) would produce the same numbers: those cannot build in Rapid30Accelerator or model reference Accelerator mode, and they hide the Python behind31a MATLAB block. The Python Code block works in both modes.3233It converts inputs to Python objects, builds a dict keyed by symbol name, calls34`exec()` with that dict as namespace, then converts outputs back to Simulink35types. The interpreter is shared with MATLAB `py.*` — same process, modules, and36state.3738- [Environment setup](references/environment.md) — pyenv, venvs, sys.path, module reloading39- [Examples](references/examples.md) — verified programmatic patterns40- [PythonObject patterns](references/pythonobject-patterns.md) — class integration and persistent state4142## When to Use4344- Running a line or block of Python each timestep inside a Simulink model45- Calling a Python function, class, or third-party library (numpy, scipy, …) from a model46- Persisting a Python object or numeric state across timesteps47- Passing a tunable parameter or a vector/matrix signal into Python48- The user describes the goal ("run my Python code in the model") without naming the block4950## When NOT to Use5152- Pure MATLAB-side Python calls with no model involved — use `py.*` directly, no block needed53- MATLAB Function blocks or S-Functions — those are different mechanisms54- Running a pretrained deep-learning model (PyTorch/TensorFlow/ONNX) — use the Deep Learning Toolbox *Model Predict* blocks (PyTorch/TensorFlow/ONNX/Custom Python Model Predict), which run via Python co-execution and are configured through the block's model-file tabs, not `SymbolSpec`55- General Simulink model construction unrelated to Python — use the `building-simulink-models` skill5657## Workflow5859Build the block in this order — **ports do not exist until symbols are60defined**, so wiring comes last. The build takes five tool calls; batch the61operations in each call:62631. **Create and save the model** (`evaluate_matlab_code`) — `model_edit` needs64 an existing model file.652. **Add and configure all blocks — one `model_edit` call.** Put the code66 parameters (`OutputCode`, `InitializeConditionsCode`, `TerminateCode`,67 `SampleTime`) in `add_block` `params`. The Python Code block is created with68 no ports. The response maps each `ref` to its `blk_N` ID:69 ```json70 [{"op":"add_block","type":"simulink/Sources/Constant","ref":"src","params":{"Value":"3"}},{"op":"add_block","type":"simulink/User-Defined Functions/Python Code","ref":"py","name":"Py","params":{"OutputCode":"y = u * 2.0","SampleTime":"1"}},{"op":"add_block","type":"simulink/Sinks/Out1","ref":"out"}]71 ```723. **Define symbols — one `evaluate_matlab_code` call; this creates the ports.**73 `SymbolSpec` is a read-only handle reached only through74 `get_param(blk,'SymbolSpec')`, and `model_edit` cannot configure symbols —75 this is the one step that uses `get_param` directly. Call `ss.addSymbol(...)`76 and set each symbol's `Scope`/`Type`/`Size` in place.774. **Wire — one `model_edit` call** using the returned IDs:78 `[{"op":"connect","target":"blk_1.y1 -> blk_2.u1"},{"op":"connect","target":"blk_2.y1 -> blk_3.u1"}]`795. **Simulate and read the result — one `evaluate_matlab_code` call.** The80 simulation compiles the block, so it is the verification; skip separate81 inspection calls unless it fails.8283The [examples](references/examples.md) give the symbol definitions and code84parameters for common patterns; read them only when the pattern isn't covered85here.8687To run the model programmatically and inspect results (sim/parsim,88`Simulink.SimulationInput`, `logsout`), use the `simulating-simulink-models` skill.8990## Block Parameters9192| Parameter | Type | Notes |93|-----------|------|-------|94| `InitializeConditionsCode` | string | Runs once at simulation start |95| `OutputCode` | string | Runs each timestep |96| `TerminateCode` | string | Runs once at simulation end |97| `SampleTime` | string | Default `"-1"` (inherited) |98| `SymbolSpec` | handle | **Read-only param** — get and mutate in place, never `set_param` back |99100**What survives from `InitializeConditionsCode` to `OutputCode`:** only imported101modules (`import m`, `import m as x`, `import pkg.sub`) and `Persistent` symbols.102Everything else in the init namespace is discarded — `from m import f` bindings,103functions, classes, and plain variables (`k = 3`) raise `NameError` in104`OutputCode`. Use the module-qualified form (`import m` → `m.f(...)`), repeat105the `from` import in `OutputCode`, or store objects in a `Persistent` symbol.106107## SymbolSpec API108109Class: `Simulink.PythonFunctionBlock.SymbolSpec` (handle object).110111```matlab112ss = get_param(blk, 'SymbolSpec');113sym = ss.addSymbol('name'); % Returns Symbol — then set properties114sym.Scope = 'Input';115sym.Type = 'double';116sym.Size = '1';117got = ss.getSymbol('name'); % Retrieve existing118ss.deleteSymbol('name'); % Remove119```120121Handle object: mutations apply immediately to the block.122123## Symbol Properties124125| Property | Values | Notes |126|----------|--------|-------|127| `Name` | char | Variable name in Python namespace |128| `Scope` | `'Input'` `'Output'` `'Parameter'` `'Persistent'` | |129| `Type` | `'double'` `'single'` `'int8'` `'int16'` `'int32'` `'int64'` `'uint8'` `'uint16'` `'uint32'` `'uint64'` `'boolean'` `'string'` `'Bus: <BusObject>'` `'fixedpoint'` `'PythonObject'` | `PythonObject` only for `Persistent`. Use lowercase `'boolean'` — `'Boolean'` is accepted by the setter but fails at compile ("not in scope"). A bus symbol names a `Simulink.Bus` object in the base workspace |130| `Size` | char | `'1'`, `'3'`, `'[2 3]'`, `'-1'` (inherit) |131| `Label` | char | Port/mask display name |132| `PortNumber` | int | Port ordering |133134## Data Type Mapping135136| Simulink | Python |137|----------|--------|138| scalar double | `float` |139| vector/matrix double | `numpy.ndarray` if numpy is available, else `array.array`. Shape follows `Size` (`'[2 3]'` ↔ `(2, 3)`); element `(i,j)` in MATLAB is `[i-1, j-1]` in Python — no transpose |140| `string` | `str` (output `str` becomes a MATLAB `string`). A root Inport fed from the workspace needs `Interpolate` off |141| bus (input) | `dict` keyed by element name — `u["a"]` |142| scalar integer | `int` |143| vector integer | `numpy.ndarray` if numpy is available, else `array.array` |144| `PythonObject` (Persistent) | any Python object |145146## Limitations147148- No variable-size signals or array of buses149- No continuous sample time with persistent variables150- No Dataflow Subsystems151- No rapid accelerator in For Each Subsystems152- No backward stepping with persistent variables153- Code generation supported (Python C API) — requires dev headers + interpreter linkage154155----156157Copyright 2026 The MathWorks, Inc.158159----