MCPInstall
matlab avatar

simulink-integrate-python-code

Use this skill when running or integrating general Python code (functions, classes, libraries) inside a Simulink model with the Python Code block (R2025a+). Not for trained neural-network models (.pt, .onnx, .h5) or deep-learning inference; use the Deep Learning Toolbox Model Predict blocks or network importers. Covers the SymbolSpec API, data-type mapping, persistent state, shared interpreter, venvs, and module reloading. Triggers: "Python Code block", "Python in Simulink", "integrate Python", "call Python from Simulink", "run my Python function/class in a model", "add Python to model", "use a Python library in a simulation".

Installs
0
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/matlab/simulink-agentic-toolkit --skill simulink-integrate-python-code
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads simulink-integrate-python-code automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

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:

  1. Create and save the model (evaluate_matlab_code) — model_edit needs an existing model file.
  2. 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"}]
    
  3. 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.
  4. 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"}]
  5. 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

ParameterTypeNotes
InitializeConditionsCodestringRuns once at simulation start
OutputCodestringRuns each timestep
TerminateCodestringRuns once at simulation end
SampleTimestringDefault "-1" (inherited)
SymbolSpechandleRead-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

PropertyValuesNotes
NamecharVariable 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
Sizechar'1', '3', '[2 3]', '-1' (inherit)
LabelcharPort/mask display name
PortNumberintPort ordering

Data Type Mapping

SimulinkPython
scalar doublefloat
vector/matrix doublenumpy.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
stringstr (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 integerint
vector integernumpy.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.


FAQ

What does the simulink-integrate-python-code skill do?

Use this skill when running or integrating general Python code (functions, classes, libraries) inside a Simulink model with the Python Code block (R2025a+). Not for trained neural-network models (.pt, .onnx, .h5) or deep-learning inference; use the Deep Learning Toolbox Model Predict blocks or network importers. Covers the SymbolSpec API, data-type mapping, persistent state, shared interpreter, venvs, and module reloading. Triggers: "Python Code block", "Python in Simulink", "integrate Python", "call Python from Simulink", "run my Python function/class in a model", "add Python to model", "use a Python library in a simulation".

How do I install simulink-integrate-python-code?

Run npx skills add https://github.com/matlab/simulink-agentic-toolkit --skill simulink-integrate-python-code in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/simulink-integrate-python-code/ (personal) or .claude/skills/simulink-integrate-python-code/ (project).

Which AI agents can use simulink-integrate-python-code?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is simulink-integrate-python-code safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains simulink-integrate-python-code?

It is published by matlab in matlab/simulink-agentic-toolkit. It has 0 recorded installs.

More from matlab/simulink-agentic-toolkit

View all →
matlab avatar

building-simulink-models

matlab/simulink-agentic-toolkit

Builds and edits Simulink, System Composer, Stateflow, and Simscape models. Use when modifying model structure, parameters, ports, connections, or Stateflow chart internals.

AI & Agents187 installs
matlab avatar

simulating-simulink-models

matlab/simulink-agentic-toolkit

Configures Simulink simulations non-destructively using SimulationInput objects — parameter overrides without modifying the model, batch sweeps via parsim, custom input signals via Dataset, and simulation data retrieval via logsout. Use when running sim()/parsim() with setVariable, setBlockParameter, setExternalInput, or when performing parameter sweeps and multi-run analysis. Not needed for one-shot simulations without configuration.

Data & Databases157 installs
matlab avatar

testing-simulink-models

matlab/simulink-agentic-toolkit

Tests Simulink models using either ephemeral Gherkin-based tests (modeltest) for quick validation or persistent tests (Simulink Test API) authored from requirements or behavioral specs. Requires Simulink Test.

Testing & QA125 installs
matlab avatar

specifying-plant-models

matlab/simulink-agentic-toolkit

Specify plant models for closed-loop simulation: system specs, architecture, build plans, validation plans. Use when creating, updating, or reviewing plant model specifications, planning plant model architecture, or planning plant model validation.

matlab avatar

specifying-mbd-algorithms

matlab/simulink-agentic-toolkit

Specify algorithms for Model-Based Design: system specs, architecture specs, implementation plans, test plans. Use when creating specifications for controllers, signal processing, diagnostics, estimators, or other algorithms authored in Simulink, Stateflow, System Composer, or MATLAB Function blocks.

AI & Agents91 installs
matlab avatar

generate-requirement-drafts

matlab/simulink-agentic-toolkit

Generates draft requirements from Simulink models. Use when drafting or updating requirement artifacts from a model. Prefers Requirements Toolbox (.slreqx) when available; falls back to structured YAML.

AI & Agents81 installs

Popular ai & agents skills

View category →
google avatar

google-agents-cli-publish

google/agents-cli

This skill should be used when the user wants to "publish an agent", "publish my ADK agent", "register an agent with Gemini", "publish to Gemini" (formerly Gemini Enterprise), or needs guidance on the agents-cli publish gemini command. Also use when the user wants to "manage agents in Agent Registry", "list/update/delete registered agents", or "register an MCP server". Covers ADK vs A2A registration modes, programmatic and interactive usage, flag reference, auto-detection from deployment metadata, Agent Registry fleet management, and troubleshooting. Part of the agents-cli skills suite. Do NOT use for deployment (use google-agents-cli-deploy).

AI & Agents588.9K installs
google avatar

google-agents-cli-eval

google/agents-cli

This skill should be used when the user wants to "run an evaluation", "evaluate my agent", "evaluate my ADK agent", "write an eval dataset", "analyze eval failures", "compare eval results", "optimize agent", or needs guidance on the Gemini platform eval methodology and the Quality Flywheel. Covers eval metrics, dataset schema, LLM-as-judge scoring, and common failure causes. Applies to any agents-cli project, whatever framework the agent is written in. Do NOT use for agent API code patterns (ADK: use google-agents-cli-adk-code), deployment (use google-agents-cli-deploy), or project scaffolding (use google-agents-cli-scaffold).

AI & Agents587.7K installs
anthropics avatar

skill-creator

anthropics/skills

Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.

OfficialAI & Agents439.9K installs
prime-skills avatar

codex-pet

prime-skills/runcomfy-agent-skills

Codex Pet generator on RunComfy. Build a Codex-compatible Codex Pet spritesheet.webp + pet.json from a single reference image, drop it into ${CODEXHOME:-$HOME/.codex}/pets/ / and Codex picks it up as a custom Codex Pet next to the 8 built-ins. This skill produces the exact Codex Pet atlas Codex expects (1536x1872 PNG/WebP, 8 cols x 9 rows, 192x208 cells, 9 animation states — idle, running-right, running-left, waving, jumping, failed, waiting, running, review). Calls OpenAI GPT Image 2 edit ONCE via the local RunComfy CLI as runcomfy run openai/gpt-image-2/edit to produce a canonical Codex Pet pose, then assembles all 9 animation rows programmatically with ImageMagick micro-transforms — no Codex Pro, no $imagegen, no OPENAIAPIKEY required, only RUNCOMFYTOKEN. Triggers on "codex pet", "create codex pet", "make codex pet", "hatch codex pet", "/hatch image", "desktop pet codex", "codex pets", "spritesheet.webp", or any explicit ask to build a custom pet for OpenAI Codex.

AI & Agents413.4K installs
leonxlnx avatar

full-output-enforcement

leonxlnx/taste-skill

Overrides default LLM truncation behavior. Enforces complete code generation, bans placeholder patterns, and handles token-limit splits cleanly. Apply to any task requiring exhaustive, unabridged output.

AI & Agents401.1K installs
obra avatar

executing-plans

obra/superpowers

Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available

AI & Agents270.5K installs