Generated banner for Matlab Deploy Embedded AI
Generated logo for Matlab Deploy Embedded AI

Matlab Deploy Embedded AI

MathWorksOfficialCreated by MathWorks

  • Skill
  • Workflow
  • Software development
  • BSD-2-Clause
  • No issues found

From the author

Deploy AI models to embedded hardware using MathWorks tools (MATLAB, Simulink, Embedded Coder). Covers two workflow patterns: (1) MathWorks-native or imported models rebuilt as dlnetwork for lean hardware, (2) direct C/C++ code generation from PyTorch and LiteRT models. Both patterns support all targets (Cortex-M/A/R, x86, GPU). Trigger when: user wants to deploy AI to embedded targets; generate C/CUDA from neural networks; compress AI models for MCU; integrate AI in Simulink for system-level simulation; import PyTorch/ONNX/TensorFlow models for embedded deployment; optimize AI for resource-constrained hardware; or use loadPyTorchExportedProgram, loadLiteRTModel, importNetworkFromPyTorch, importNetworkFromONNX, importNetworkFromTensorFlow, importNetworkFromKeras, dlquantizer, exportNetworkToSimulink, or Embedded Coder with AI models.
— the description by MathWorks

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach for deploying AI models to embedded targets such as Cortex-M, Cortex-A/R, x86, and GPU. It supports two primary deployment patterns: rebuilding models as native dlnetwork objects for optimized hardware deployment, or direct C/C++ code generation from PyTorch and LiteRT models. The skill covers the entire lifecycle, including model import, compression (quantization, pruning, projection), system-level simulation in Simulink, and code generation using MATLAB Coder and Embedded Coder.

What it does

  • Imports and converts external AI models (PyTorch, ONNX, TensorFlow, Keras) into MATLAB-native formats.
  • Optimizes models for resource-constrained hardware via quantization, pruning, and projection.
  • Integrates AI inference into Simulink models for closed-loop system simulation.
  • Generates optimized C/C++ or CUDA code for various embedded hardware targets.
  • Validates numerical equivalence between original models and generated code.
  • Provides a decision framework to select the optimal deployment pattern based on hardware and performance needs.

When to use it

  • When you need to deploy a trained neural network to embedded hardware.
  • When you must compress an AI model to fit within memory or latency constraints of an MCU.
  • When you need to integrate AI inference into a Simulink system model.
  • When you need to generate C/C++ code from PyTorch or LiteRT models for production deployment.
  • When you require verification of numerical accuracy across model transformations.

Advantages

  • Supports a wide range of embedded targets including ARM Cortex and GPU architectures.
  • Enables system-level verification through Simulink integration before hardware deployment.
  • Provides advanced compression techniques to optimize performance on resource-constrained devices.
  • Ensures reproducibility through script-based execution and numerical validation steps.
  • Offers flexible deployment paths for both native MATLAB models and external framework models.

Usage examples

“How do I deploy my trained MATLAB neural network to an ARM Cortex-M processor?”
The agent will initiate the Project Discovery process to confirm the target hardware and model type, then guide you through the Pattern 1 workflow, including potential compression and code generation steps.
“I have a PyTorch model and need to generate C++ code for an x86 target. Which pattern should I use?”
The agent will identify this as a Pattern 2 scenario, confirm the requirements, and walk you through the direct code generation workflow using the PyTorch support package.
“Can you help me quantize my imported ONNX model for an embedded device?”
The agent will guide you through importing the model as a dlnetwork, performing quantization using the dlquantizer, and validating the accuracy before generating the final code.
“I need to verify if my model is compatible with code generation.”
The agent will run the analysis function to check for unsupported layers and provide a report on compatibility for your specific target library.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/matlab/matlab-deploy-embedded-ai/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip matlab-deploy-embedded-ai.zip -d .agents/skills

Documentation by MathWorks

Embedded AI for Engineered Systems

Deploy AI models to embedded hardware using MATLAB® and Simulink®. This skill is written specifically for MATLAB R2026a and uses APIs, functions, and workflows introduced in that release. It covers the complete lifecycle: model creation or import, verification, compression, system-level simulation, and code generation for resource-constrained targets.

Requires MATLAB R2026a or newer. Core toolboxes: Deep Learning Toolbox, Statistics and Machine Learning Toolbox, MATLAB Coder, Embedded Coder, Simulink, and Fixed-Point Designer. Workflow-specific support packages are checked during Environment Discovery. The MATLAB and Simulink Agentic Toolkits must be available so the agent can drive a live MATLAB and Simulink session through MCP tools.

When to Use

  • Deploying a trained neural network (MATLAB-native or imported) to embedded hardware

  • Generating C or CUDA code from a deep learning model for ARM Cortex-M/A/R, x86, or GPU targets

  • Deploying imported PyTorch, ONNX, TensorFlow, or LiteRT models to embedded targets (import step handled by /matlab-import-external-ai-model)

  • Compressing AI models (quantization, pruning, projection) to fit resource-constrained hardware

  • Integrating AI inference into a Simulink system model for closed-loop simulation before code generation

  • Using loadPyTorchExportedProgram, importNetworkFromPyTorch, importNetworkFromONNX, importNetworkFromTensorFlow, dlquantizer, exportNetworkToSimulink, or Embedded Coder with AI models

  • Choosing between MathWorks-native code generation and direct PyTorch/LiteRT code generation

When NOT to Use

  • Training a model purely for research with no deployment target — use Deep Learning Toolbox documentation directly

  • Deploying to cloud/server endpoints (no embedded target) — use MATLAB Production Server or MATLAB Compiler SDK

  • Working with classical ML models (decision trees, SVMs, ensembles) that aren't neural networks — use Statistics and Machine Learning Toolbox codegen workflows directly. Note: fitcnet/fitrnet neural network models ARE covered by this skill

  • Generating code for non-AI Simulink models — use standard Embedded Coder workflows

  • Converting between model formats without an embedded deployment goal (e.g., ONNX to MATLAB for desktop inference only)

Workflow Pattern Selection

This skill uses two deployment patterns:

  • Pattern 1 — MATLAB Network Codegen: Import or build a dlnetwork, optionally compress it, then generate C/C++ via MATLAB Coder or export to Simulink. See references/pattern1/workflow.md.

  • Pattern 2 — PyTorch/LiteRT Direct Codegen: Load a PyTorch (.pt2) or LiteRT (.tflite) model directly and generate C/C++ without converting to a dlnetwork. See references/pattern2/workflow.md.

Decision Tree

Primary discriminator for external models: deployment capabilities + hardware class.

Q1: Where does the AI model come from?
 |
 +-- Trained in MATLAB, or requires training in MATLAB -------> Pattern 1
 |
 +-- External framework (PyTorch, TF, ONNX, Keras) --> Q2
      |
      Q2: Does the deployment need any of these?
       |  - Quantization (INT8 via dlquantizer)
       |  - Pruning or projection
       |  - Weight inspection / modification
       |  - exportNetworkToSimulink integration
       |
       +-- YES --> Pattern 1 (import as dlnetwork)
       |
       +-- NO ---> Q3
            |
            Q3: What is the deployment target?
             |
             +-- Cortex-M: Pattern 1
             |     (compression and Simulink verification typically needed)
             |
             +-- x86 / GPU:
             |     +-- PyTorch (.pt2) or LiteRT (.tflite) --> Pattern 2
             |     +-- ONNX, TF, Keras --> Pattern 1 (convert to ONNX recommended)
             |
             +-- Cortex-A/R:
                   +-- Small model --> Pattern 1
                   |     (import as dlnetwork, then codegen)
                   +-- Large model:
                        +-- PyTorch (.pt2) or LiteRT (.tflite) --> Pattern 2
                        +-- ONNX, TF, Keras --> Pattern 1 (convert to ONNX recommended)
Pattern Summary
PatternWhen to UsePrimary Toolchain
1 — MATLAB Network CodegenModel trained in MATLAB, OR external model needing compression/quantization/Simulink export/weight inspection, OR Cortex-M targetsMATLAB Coder™ / Embedded Coder™
2 — PyTorch/LiteRT Direct CodegenExternal PyTorch (.pt2) or LiteRT (.tflite) model on x86/GPU/Cortex-A targets; shorter path to C code without compressionMATLAB Coder™ + PyTorch & LiteRT SPKG

Pattern 2's generated C is portable to any target, but Cortex-M deployments typically require Pattern 1 capabilities (compression, Simulink verification).

Import step (Pattern 1): For PyTorch/ONNX/Keras/TensorFlow model import, use /matlab-import-external-ai-model. This skill takes over after import for the compression, Simulink integration, and code generation phases.

Pattern 1 vs Pattern 2 Capability Comparison
CapabilityPattern 1 (dlnetwork)Pattern 2 (PyTorch/LiteRT direct)
C code generationYesYes
Target: Cortex-M, Cortex-A/R, x86, GPUYesYes
Weight inspection / modificationYesNo
dlquantizer (INT8)YesNo
Projection (compressNetworkUsingProjection)YesNo
PruningYesNo
Simulink integrationYes (exportNetworkToSimulink)Yes (PyTorch SPKG Simulink blocks)
Combined compressionYesNo
Speed to first C codeSlowerFaster

Rule of thumb: Choose Pattern 1 when you need to compress, quantize, inspect weights, or use exportNetworkToSimulink — or when the model is already a dlnetwork, or when targeting Cortex-M. Choose Pattern 2 when the model is already in PyTorch (.pt2) or LiteRT (.tflite) format and you want the shorter path to C code without compression.

Stats/ML models (fitrnet/fitcnet): These follow Pattern 1 but have their own Simulink integration path. Use the RegressionNeuralNetwork Predict block (for fitrnet) or ClassificationNeuralNetwork Predict block (for fitcnet) from the Statistics and Machine Learning Toolbox library — do NOT use exportNetworkToSimulink (which is for dlnetwork only). Configure simulation programmatically with Simulink.SimulationInput.

Common Start: Prerequisites

Regardless of pattern, always begin with these two prerequisite steps before entering the pattern-specific phases (which start at Phase 1):

  1. Environment Discovery (silent): Load references/shared/environment-setup.md

  2. Project Discovery (interactive): Load references/shared/project-discovery.md

Project Discovery determines the workflow pattern via the decision tree above.

Do Not Use (Legacy Functions)

LegacyModern Replacement
trainNetwork / train (for DL)trainnet
DAGNetwork / SeriesNetwork / networkdlnetwork
taylorPrunableNetwork / updateScore / updatePrunablescompressNetworkUsingTaylorPruning (when trainable with trainnet); use taylorPrunableNetwork for custom training loops
csvread / xlsreadreadmatrix / readtable
datenumdatetime

For legacy import functions (importONNXNetwork, importKerasNetwork, etc.), see /matlab-import-external-ai-model which handles all model import workflows.

Global Rules

Advisory vs Execution Mode

Distinguish between two modes based on the user's intent:

  • Advisory ("How should I approach this?", "What workflow?", "Which pattern?"): Answer the routing question directly — state the recommended Pattern, explain why, and outline the high-level steps. Do NOT enter Environment Discovery or start asking prerequisite questions. After giving the recommendation, ask if the user wants to begin execution.

  • Execution ("Deploy my model", "Walk me through", "Write the script"): Enter the full prerequisite flow (Environment Discovery → Project Discovery → step-by-step phases).

ALWAYS
  • Check toolboxes via detect_matlab_toolboxes and support packages via matlabshared.supportpkg.getInstalled before any workflow step

  • If a support package is missing, ask the user to download from Add-On Explorer -- never install on their behalf

  • Guide the user step-by-step -- one phase at a time

  • Use consistent data partitioning (e.g., fixed indices or a stored partition object) for reproducibility

  • Verify numerical equivalence at each transformation step

  • Generate MEX for desktop validation before generating C code for target

  • Use single precision for all inference inputs

  • Script-based execution: For each workflow step done in MATLAB, create a .m script file and execute it with run_matlab_file or evaluate_matlab_code. Do NOT run ad-hoc MATLAB commands without first writing the script file. If a script needs changes, edit the script file and re-run it. This gives users full visibility into what code is being executed and enables reproducibility. IMPORTANT: run_matlab_file sets the working directory to the script's folder. Always use absolute paths (via fullfile) for model files, data, and saved outputs — never rely on pwd or relative paths.

  • Pause after each workflow step: After every workflow step completes, pause and explicitly ask the user for permission to proceed to the next step. The goal is to let the user read/inspect the MATLAB scripts you created, review results, and ask questions before moving on.

  • Deep Network Designer: When a model is trained in MATLAB, imported, or rebuilt as a native dlnetwork, load it in Deep Network Designer (deepNetworkDesigner(net)) so the user can visually inspect the architecture. Announce this action and wait for user acknowledgment before proceeding.

  • Numerical equivalency tests (import workflows): For any import from PyTorch or ONNX:

    1. Run inference on the original model (via bundled Python for PyTorch, or ONNX runtime) to collect ground-truth reference data. Do NOT use the imported MATLAB model as reference — for PyTorch imports in R2026a, custom autogenerated layers may not support code generation and the model may need to be rebuilt natively. (ONNX autogenerated layers have supported code generation since R2025a and may not require a rebuild.)

    2. Run the same inputs through the rebuilt native MATLAB model and compare against ground truth

    3. After compression, report the accuracy delta vs. the uncompressed baseline (MAE, max error, % accuracy drop). Compute these from variables in the current run — never hardcode numeric values into fprintf/disp strings, because re-running the script with different inputs or a different model will then print stale numbers.

    4. Run tests to validate numerical equivalence between: compressed model in MATLAB, compressed model in Simulink, and final generated code

  • Test count proposal: Before running numerical equivalency tests, propose how many tests you plan to run and explain why (considering model complexity, output range, class count, etc.). Wait for user agreement or correction before proceeding.

  • Code generation report: Do NOT open the code generation report automatically — it opens a GUI that is not useful in an agentic workflow. Only open if the user explicitly requests it.

  • Look up function signatures from MATLAB's help or the online reference page, not from this skill. Argument lists, name-value pair (NVP) defaults, and supported-layer enumerations live in MATLAB's help <function> output and on the function's reference page. Use those as the source of truth instead of any inline parameter table in this skill — inline tables go stale across releases and burn context. This skill only flags name-value arguments that materially change the recipe (e.g., ValidationThreshold for accuracy-budgeted pruning). Lookup procedure:

    1. First try help <function> in the live MATLAB session. Fast and reflects the actually-installed release of the toolbox or support package.

    2. If help returns only a stub like "Run doc <function> for more information." — common for support-package functions whose help redirects to the browser doc — fall back to the agent's web browsing of the online reference page at https://www.mathworks.com/help/<product>/ref/<funcname>.html (lower-case function name). Extract every name-value argument with its default value, formatted as a markdown table, quoting defaults verbatim.

    3. If the function is not found at all (which <func> returns "not found") on a system that has the relevant support package installed, the support package is likely on a stale build. Ask the user to update via Add-On Explorer rather than working around the missing function.

  • Compression decision flow: At the start of Phase 5 (Pattern 1), load references/pattern1/compression-decision.md and walk the user through the question flow (hardware + Simulink availability, primary goal, retraining tolerance). Pick the compression and code generation path based on the answers. Compression is not mandatory and the optimal combination of pruning, projection, and quantization depends on the goal — for example, on Cortex-M with a latency-bound LSTM model, the float32 path with CMSIS-DSP outperforms the quantized path because CMSIS-NN provides no INT8 kernel for recurrent layers.

ASK FIRST
  • Before each phase transition: "Is this step relevant to your project?" (some phases may not apply)

  • Before data splitting: "Do you have existing train/val/test splits, or should I partition?" (avoids overwriting user's partitioning)

  • Before model selection: "What problem type (classification/regression/sequence) and any size constraints?" (determines architecture)

  • Before Simulink: "Do you have an existing Simulink model to integrate into?" (determines export vs standalone)

  • Before quantization: "Does your target support floating-point, or is integer-only required?" (determines quantization path)

  • Before code generation: "What is the target hardware?" (determines Coder configuration and CRL)

  • Before compression and code generation (Pattern 1): walk the user through the decision flow in references/pattern1/compression-decision.md — hardware target + Simulink availability, primary goal, retraining tolerance. The answers determine the compression techniques and the code-replacement library to use. Even if the hardware target is already stated, you MUST still ask about the primary deployment goal (flash, SRAM, latency, accuracy) and present the user with the recommended recipe for confirmation before executing any compression step.

NEVER
  • Present the entire workflow at once

  • Skip Environment Discovery or Project Discovery

  • Open, load, or inspect user data before Project Discovery is confirmed

  • Use legacy functions listed in "Do Not Use" section

  • Assume toolbox or support package availability without checking

  • Install support packages on the user's behalf

  • Promise hardware-agnostic performance or "deploy anywhere"

  • Generate DAGNetwork, SeriesNetwork, or network objects

  • Run MATLAB commands directly in the MCP server without creating a script file first

  • Skip numerical equivalency testing when using imported external models

  • Proceed to the next workflow step without explicit user permission

  • Apply compression without first walking the user through the decision flow in compression-decision.md

  • Use the imported model (with custom autogenerated layers) as numerical ground truth — always validate against the original model via bundled Python

  • Pass a [C × T] array with format "CBT" to a sequence model — always reshape to [C × 1 × T] for single-sequence inference

  • Pass a dlnetwork to prepareNetwork — in R2026a the function takes a dlquantizer object (prepareNetwork(quantObj)) and mutates it in place. The legacy net = prepareNetwork(net) form is no longer defined


This skill covers C/C++ code generation for CPU targets (Cortex-M, Cortex-A/R, x86) via MATLAB Coder and Embedded Coder, and GPU targets (CUDA/TensorRT) via Pattern 2's DeepLearningConfig options. The following deployment targets use different toolchains and are NOT covered:

TargetToolchainNotes
FPGA / SoCHDL Coder + Deep Learning HDL ToolboxGenerates HDL (VHDL/Verilog) from dlnetwork
PLCSimulink PLC CoderGenerates Structured Text for PLCs from Simulink models

If the user's target falls into one of these categories, inform them that this skill does not cover that workflow and suggest the relevant toolchain.


MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be trademarks or registered trademarks of their respective holders.

Copyright 2026 The MathWorks, Inc.

Files

references/pattern1/workflow.md

Pattern 1: MathWorks-Native Models for Lean Hardware

Interactive, step-by-step workflow for designing, training (or importing), verifying, compressing, and deploying AI models to resource-constrained embedded targets using MATLAB and Simulink.

When to Use

  • Model is trained in MATLAB (already a dlnetwork)

  • Model is imported from ONNX and user needs compression (quantization, pruning, projection)

  • User needs weight inspection or modification

  • User needs exportNetworkToSimulink integration for system-level simulation

  • User mentions: virtual sensors, anomaly detection, predictive maintenance, state estimation, time-series classification, signal-based AI

  • External model does not fit target memory and needs compression before deployment

When NOT to Use

  • User has a PyTorch (.pt2) or LiteRT (.tflite) model that already fits the target and just needs C code quickly → Pattern 2

  • User wants NPU or FPGA deployment (not covered by this skill)

  • User wants to train purely in Python without MATLAB integration

  • User is working with generative AI, LLMs, or foundation models

Rules

ALWAYS
  • Complete Environment Discovery + Project Discovery (from shared/) before any technical work

  • Check toolboxes and support packages before every phase

  • Create .m scripts for each workflow step; execute via run_matlab_file -- never run ad-hoc MATLAB commands without first writing the script file

  • Pause after each step and ask user for permission to proceed; let them inspect scripts

  • Use trainnet for DL training (produces dlnetwork), fitcnet/fitrnet for MLPs

  • Use consistent data partitioning for reproducibility

  • Format sequence data as cell arrays of [T x C] single matrices for trainnet

  • Use networkDistributionDiscriminator for OOD detection (not custom implementations)

  • Use exportNetworkToSimulink with the compressed model when compression is applied

  • For fixed-point C: export the quantized network (quantize() output) to Simulink

  • For float32 C via direct MATLAB Coder: lstmProjectedLayer and gruProjectedLayer are codegen-supported; ProjectedLayer is supported when its contents are stateless. Call unpackProjectedLayers if a ProjectedLayer wraps a stateful LSTM/GRU. Quantized networks (quantize() output) are not supported by coder.loadDeepLearningNetwork — use the Simulink path instead.

  • Generate MEX for desktop validation before generating C code for target

  • Verify training calls with a tiny input (2-5 samples, 1-2 epochs) before full training

  • Warn about missing Embedded Coder when doing code generation

  • Load trained/imported/rebuilt models in Deep Network Designer for user inspection

  • Walk the user through the compression-decision question flow (load compression-decision.md) at the start of Phase 5 to choose the right combination of pruning, projection, and quantization based on hardware target, deployment goal, and retraining tolerance

  • Propose test count for numerical equivalency tests and get user agreement before running

  • Ask the user if they want to open the code generation report after code generation completes

NEVER
  • Use banned legacy functions (see top-level SKILL.md)

  • Assume toolbox or support package availability without checking

  • Install support packages on the user's behalf

  • Implement OOD detection, pruning, projection, or quantization with custom code

  • Pass a quantized network (output of quantize()) to coder.loadDeepLearningNetwork

  • Generate DAGNetwork, SeriesNetwork, or network objects

  • Use predict(discriminator, ...) -- use isInNetworkDistribution / distributionScores

  • Skip Environment Discovery or Project Discovery


Workflow Phases

7 sequential phases. The workflow is iterative -- compression or Simulink results may require returning to earlier phases. At each phase boundary, ask whether the next phase is relevant.

Prerequisites (already completed before this file is loaded):

  • Environment Discovery (silent) — via references/shared/environment-setup.md

  • Project Discovery (interactive) — via references/shared/project-discovery.md

The Project Summary determines whether Phase 3 uses the training or import sub-path.

Phase 1: Workflow Plan

Based on the Project Summary, determine applicable phases and present a tailored plan.

Problem-to-approach mapping:

Problem TypeRecommended ApproachToolbox
Tabular classificationfitcnetStats/ML
Tabular regressionfitrnetStats/ML
Time-series / sequenceLSTM, GRU, or 1D-CNN via trainnetDLT
Signal classification1D-CNN via trainnetDLT
Small image classificationCNN via trainnetDLT
Anomaly detection (tabular)Autoencoder via trainnetDLT
External model importImport + native rebuildDLT + Converter

Present the plan and get confirmation before proceeding.

Pause. "Does this workflow plan match your needs?"

Phase 2: Data Preparation

Load data-preparation.md.

  • Load and inspect data for the first time

  • Handle preprocessing, normalization, feature engineering

  • Split data with rng("default") and cvpartition

  • Format sequences as cell arrays of [T x C] single matrices

Pause. "Shall we proceed to model design?"

Phase 3: AI Modeling

Two sub-paths based on Project Discovery:

Path A: MATLAB-Native Training

Defer to the matlab-train-network skill for training guidance.

  • Confirm approach from Phase 1 (Workflow Plan)

  • Create a training script (.m file) and execute via run_matlab_file

  • Train with trainnet (DL) or fitcnet/fitrnet (MLP)

  • For LSTM/GRU: set GradientThreshold=1; use OutputNetwork="best-validation"

  • Verify training call with tiny input before full run

  • Evaluate on test set; check accuracy requirements from Project Discovery

  • Check deployed size: na = analyzeNetwork(net, Plots='none'); na.TotalLearnables

  • Load trained model in Deep Network Designer (deepNetworkDesigner(net)) for user inspection

Path B: External Model Import and Native Rebuild

Use /matlab-import-external-ai-model for the import step (handles model preparation in Python, import arguments, troubleshooting, and numeric validation).

Then load native-rebuild-preparation.md.

  • Extract weights from imported network

Then load native-rebuild-patterns.md.

  • Build fresh native dlnetwork using standard MATLAB layers

  • Transfer weights from imported to native network

  • Run numerical equivalency tests:

    1. Propose test count and rationale to user; wait for agreement

    2. Collect reference outputs from original model

    3. Run same inputs through imported/rebuilt MATLAB model

    4. Compare and report: MAE, max error, cosine similarity

    5. Verify max error < 1e-5 for identical architectures

  • Load rebuilt model in Deep Network Designer (deepNetworkDesigner(netNative)) for user inspection

If custom layers are needed for the rebuild, also load custom-layers-codegen.md.

Pause. "Shall we proceed to AI verification?"

Phase 4: AI Verification

Load references/shared/ai-verification.md.

  • Always recommend OOD detection with networkDistributionDiscriminator

  • Convert fitcnet/fitrnet to dlnetwork for verification if needed

  • Check AI Verification Library availability for formal verification

  • Suggest empirical testing: adversarial, corner-case, distribution shift

Pause. "Shall we proceed to model compression?"

Phase 5: Model Compression and Quantization

Step 5.1 — Walk the user through the decision flow. Load compression-decision.md FIRST. Ask the user about their hardware target (combined with Simulink availability), primary deployment goal (flash, SRAM, latency, integer-only, accuracy), and retraining tolerance. Skip the retraining question if the dataset is unavailable. Present the recommended path and confirm with the user before applying any technique.

Step 5.2 — Apply the chosen techniques. Load compression.md for the technique-level details.

  • Compression order when multiple techniques apply: (1) Pruning, (2) Projection, (3) Quantization

  • Use official functions only -- no custom implementations

  • After each compression step, report the accuracy delta vs the uncompressed baseline on a held-out set. The compressed network is not expected to be numerically equivalent to the original; the relevant question is how much the deployment-relevant metric (classification accuracy, regression MAE/RMSE, etc.) has degraded and whether the budget from Project Discovery still holds.

  • Revisit verification (Phase 4) after compression

  • Re-check accuracy requirements from Project Discovery against compressed model

  • If the accuracy-vs-size tradeoff is unacceptable: iterate back to Phase 3

Step 5.3 — Try alternative paths when retraining is acceptable. For an LSTM-heavy flash-bound model, generate both project+quantize and quantize-only variants, measure flash and MAE, and let the user choose. Don't assume the combined pipeline is best without comparison.

Pause. "Shall we proceed to Simulink integration?"

Load simulink-integration.md.

  • For fixed-point deployment: export the quantized network via exportNetworkToSimulink(qNet) (produces fixed-point Simulink blocks → integer C code)

  • For float32 deployment: export the projected (or pruned) network directly. In R2026a, exportNetworkToSimulink accepts projected networks; unpackProjectedLayers is no longer required for the Simulink path. For the direct MATLAB Coder path, lstmProjectedLayer and gruProjectedLayer are codegen-supported; unpack only when a ProjectedLayer wraps a stateful LSTM/GRU.

  • If placeholder layers appear, load placeholder-blocks.md

  • For fitcnet/fitrnet: use Stats/ML Predict blocks

  • Open-loop fallback if no Simulink model available

  • Simulate with Simulink.SimulationInput + sim()

  • Run numerical equivalency tests comparing Simulink outputs to compressed MATLAB model outputs. Report MAE, max error. Ensure results are within expected tolerances.

Pause. "Shall we proceed to code generation?"

Phase 7: Code Generation and Deployment

Load codegen-embedded.md.

  • Check for MATLAB Coder, Simulink Coder, Embedded Coder

  • Generate MEX first for desktop validation

  • Run numerical equivalency tests comparing MEX/generated code outputs to Simulink and MATLAB compressed model outputs. This validates the full pipeline: original model → MATLAB → compressed → Simulink → C code.

  • Generate C code for target hardware

  • Ask the user if they want to open the code generation report to inspect generated code, warnings, and metrics

  • Present deployment summary and checklist


Deliverable Structure

When generating scripts, organize as:

project_name/
  embeddedAIWorkflow.mlx          Main Live Script (orchestration)
  scripts/
    step01_prepareData.m          Data preprocessing (executed via run_matlab_file)
    step02_buildNetwork.m         Network construction
    step03_trainModel.m           Training wrapper
    step04_evaluateModel.m        Evaluation metrics
    step05_compressModel.m        Compression pipeline
    step06_exportToSimulink.m     Simulink export
    step07_generateCode.m         Code generation
    step08_verifyEquivalency.m    Full pipeline numerical equivalency tests
  helpers/
    checkOOD.m                    OOD detection (codegen-ready)
    predictForCodegen.m           Codegen entry-point (codegen-ready)
  data/

Script-based execution: Each stepXX_*.m script is self-contained and executed via run_matlab_file. This gives users full visibility into what code runs at each step and enables them to inspect, modify, and re-run individual steps. Never run ad-hoc commands in the MCP server.

Functions for code generation must use arguments blocks, avoid dynamic features, and use single precision.

Copyright 2026 The MathWorks, Inc.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an MCP server

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
MathWorks
Publisher
MathWorks (Official)
Source
matlab/matlab-agentic-toolkit · skills-catalog/ai-and-statistics/matlab-deploy-embedded-ai · commit 2a7f215
Licence
BSD 2-Clause License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE.md)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by MathWorks or MathWorks.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-deploy-embedded-ai.zip