Matlab Deploy Embedded AI
MathWorksOfficialCreated by MathWorks
- Skill
- Workflow
- Software development
- BSD-2-Clause
- No issues found
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
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/matlab/matlab-deploy-embedded-ai/downloadUnzip 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 modelsChoosing 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/fitrnetneural network models ARE covered by this skillGenerating 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. Seereferences/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
| Pattern | When to Use | Primary Toolchain |
|---|---|---|
| 1 — MATLAB Network Codegen | Model trained in MATLAB, OR external model needing compression/quantization/Simulink export/weight inspection, OR Cortex-M targets | MATLAB Coder™ / Embedded Coder™ |
| 2 — PyTorch/LiteRT Direct Codegen | External PyTorch (.pt2) or LiteRT (.tflite) model on x86/GPU/Cortex-A targets; shorter path to C code without compression | MATLAB 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
| Capability | Pattern 1 (dlnetwork) | Pattern 2 (PyTorch/LiteRT direct) |
|---|---|---|
| C code generation | Yes | Yes |
| Target: Cortex-M, Cortex-A/R, x86, GPU | Yes | Yes |
| Weight inspection / modification | Yes | No |
| dlquantizer (INT8) | Yes | No |
| Projection (compressNetworkUsingProjection) | Yes | No |
| Pruning | Yes | No |
| Simulink integration | Yes (exportNetworkToSimulink) | Yes (PyTorch SPKG Simulink blocks) |
| Combined compression | Yes | No |
| Speed to first C code | Slower | Faster |
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):
Environment Discovery (silent): Load
references/shared/environment-setup.mdProject Discovery (interactive): Load
references/shared/project-discovery.md
Project Discovery determines the workflow pattern via the decision tree above.
Do Not Use (Legacy Functions)
| Legacy | Modern Replacement |
|---|---|
trainNetwork / train (for DL) | trainnet |
DAGNetwork / SeriesNetwork / network | dlnetwork |
taylorPrunableNetwork / updateScore / updatePrunables | compressNetworkUsingTaylorPruning (when trainable with trainnet); use taylorPrunableNetwork for custom training loops |
csvread / xlsread | readmatrix / readtable |
datenum | datetime |
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_toolboxesand support packages viamatlabshared.supportpkg.getInstalledbefore any workflow stepIf 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
singleprecision for all inference inputsScript-based execution: For each workflow step done in MATLAB, create a
.mscript file and execute it withrun_matlab_fileorevaluate_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_filesets the working directory to the script's folder. Always use absolute paths (viafullfile) for model files, data, and saved outputs — never rely onpwdor 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:
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.)
Run the same inputs through the rebuilt native MATLAB model and compare against ground truth
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/dispstrings, because re-running the script with different inputs or a different model will then print stale numbers.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.,ValidationThresholdfor accuracy-budgeted pruning). Lookup procedure:First try
help <function>in the live MATLAB session. Fast and reflects the actually-installed release of the toolbox or support package.If
helpreturns 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 athttps://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.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.mdand 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, ornetworkobjectsRun 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.mdUse 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 inferencePass a
dlnetworktoprepareNetwork— in R2026a the function takes adlquantizerobject (prepareNetwork(quantObj)) and mutates it in place. The legacynet = prepareNetwork(net)form is no longer defined
Related Workflows (Out of Scope)
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:
| Target | Toolchain | Notes |
|---|---|---|
| FPGA / SoC | HDL Coder + Deep Learning HDL Toolbox | Generates HDL (VHDL/Verilog) from dlnetwork |
| PLC | Simulink PLC Coder | Generates 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
- ATTRIBUTION.mdAdded by AutoGineer1.0 KiB
- LICENSELicence file added by AutoGineer1.4 KiB
- SKILL.md18.1 KiB
- manifest.yaml588 B
- references/pattern1/codegen-embedded.md19.3 KiB
- references/pattern1/compression-classical-ml.md2.2 KiB
- references/pattern1/compression-decision.md9.8 KiB
- references/pattern1/compression-projection.md7.9 KiB
- references/pattern1/compression-pruning.md2.7 KiB
- references/pattern1/compression-quantization.md13.6 KiB
- references/pattern1/compression.md13.1 KiB
- references/pattern1/custom-layers-codegen.md7.9 KiB
- references/pattern1/data-preparation.md5.3 KiB
- references/pattern1/native-rebuild-patterns.md9.4 KiB
- references/pattern1/native-rebuild-preparation.md14.7 KiB
- references/pattern1/placeholder-blocks.md14.6 KiB
- references/pattern1/simulink-integration.md22.9 KiB
- references/pattern1/troubleshooting.md18.3 KiB
- references/pattern1/workflow.md12.1 KiB
- references/pattern2/architecture-patterns.md5.0 KiB
- references/pattern2/coder-configuration.md6.8 KiB
- references/pattern2/pytorch-export.md4.7 KiB
- references/pattern2/troubleshooting.md7.1 KiB
- references/pattern2/verification-testing.md10.7 KiB
- references/pattern2/workflow.md5.6 KiB
- references/shared/ai-verification.md4.3 KiB
- references/shared/environment-setup.md4.6 KiB
- references/shared/project-discovery.md4.2 KiB
references/pattern1/codegen-embedded.md
Code Generation for Embedded Targets
Patterns for generating embedded C/C++ code from trained AI models using MATLAB Coder, Simulink Coder, and Embedded Coder.
Toolbox Requirements
| Toolbox | Purpose | Required? |
|---|---|---|
| MATLAB Coder | Generate C/C++ from MATLAB code | Yes |
| Simulink Coder | Generate code from Simulink models | Yes (if using Simulink) |
| Embedded Coder | Optimized embedded code + IDE integration | Strongly recommended |
Embedded Coder Warning
If Embedded Coder is NOT available, always inform the user:
"Warning: Embedded Coder is not installed. Code generated by MATLAB Coder or Simulink Coder alone may not be optimized for your embedded target. Without Embedded Coder, you may experience:
Larger code footprint (ROM/RAM)
Suboptimal execution speed
Limited target-specific optimizations
No direct IDE integration
Code may not meet production coding standards (MISRA, CERT)
For production deployment on resource-constrained hardware, installing Embedded Coder is strongly recommended."
Network Compatibility for Code Generation
Before creating a predict function, ensure the network is codegen-compatible:
| Network Type | Direct MATLAB Coder (coder.loadDeepLearningNetwork) | Simulink Path (exportNetworkToSimulink → slbuild) |
|---|---|---|
Standard dlnetwork | Supported (float32 C) | Supported (float32 C) |
Projected network (lstmProjectedLayer, gruProjectedLayer, or ProjectedLayer over conv/FC/stateful-I/O LSTM/GRU) | Supported — generic C/C++ only, no MKL-DNN / ARM Compute acceleration. A ProjectedLayer over a stateful LSTM/GRU is not supported; unpack with unpackProjectedLayers(net) first | Supported directly in R2026a — exportNetworkToSimulink accepts projected networks; no unpack required |
Quantized network from quantize() | NOT supported — use the pre-quantized network | SUPPORTED — generates fixed-point C (int8/int16/int32). This is the recommended path for quantized deployment. See Export Quantized Network to Simulink |
Validate Codegen Compatibility
Before generating code, run the analysis function to check for unsupported layers:
analyzeNetworkForCodegen(netNative, TargetLibrary='none');Set TargetLibrary to match your deployment target if not using library-free codegen
(e.g., 'mkldnn', 'arm-compute', 'cudnn', 'tensorrt').
This reports any layers or operations that will fail during code generation.
Code Generation from MATLAB (MATLAB Coder)
Step 1: Create a Predict Function
Wrap the trained model in a standalone prediction function suitable for code generation.
For dlnetwork (tabular/image data):
function y = predictDLNet(x)
%#codegen
persistent net;
if isempty(net)
net = coder.loadDeepLearningNetwork('trainedNet.mat');
end
dlX = dlarray(x, 'BC'); % x is [1 x numFeatures] (Batch x Channel)
dlY = predict(net, dlX);
y = extractdata(dlY);
endFor dlnetwork (LSTM/GRU sequence models -- stateful, one step at a time):
function y = predictSeqDLNet(x)
%#codegen
persistent net;
if isempty(net)
net = coder.loadDeepLearningNetwork('trainedSeqNet.mat');
end
dlX = dlarray(x, 'CB'); % x is [numFeatures x 1] (Channel x Batch)
[dlY, state] = predict(net, dlX);
net.State = state;
y = extractdata(dlY);
endFor fitcnet:
function [label, score] = predictClassifier(x)
%#codegen
persistent mdl;
if isempty(mdl)
mdl = loadLearnerForCoder('trainedClassifier.mat');
end
[label, score] = predict(mdl, x);
endFor fitrnet:
function y = predictRegressor(x)
%#codegen
persistent mdl;
if isempty(mdl)
mdl = loadLearnerForCoder('trainedRegressor.mat');
end
y = predict(mdl, x);
endStep 2: Configure Code Generation
Standard MATLAB Coder configuration:
% Create configuration for static library
cfg = coder.config("lib");
% Set target language
cfg.TargetLang = "C";
% Configure for ARM Cortex-M target
cfg.HardwareImplementation.ProdHWDeviceType = "ARM Compatible->ARM Cortex-M";
% cfg.PurelyIntegerCode = true; % Uncomment only if target has no FPU and
% % you are generating fixed-point code
% Optimize for speed or size
cfg.BuildConfiguration = "Faster Runs"; % or "Smaller Size"Embedded Coder configuration with native dlnetwork support:
cfg = coder.config('lib', 'ecoder', true);
cfg.TargetLang = 'C';
% Use 'none' for native dlnetwork (no third-party deep learning library)
cfg.DeepLearningConfig = coder.DeepLearningConfig('none'); % default, stated explicitly
% For MCUs without filesystem, keep all weights in source files
cfg.LargeConstantGeneration = 'KeepInSourceFiles';
% ARM Cortex-M (single-core MCU)
cfg.HardwareImplementation.ProdHWDeviceType = 'ARM Compatible->ARM Cortex-M';
cfg.EnableOpenMP = false;ARM Cortex-A configuration (multi-core SBC):
% cfg.Hardware = coder.hardware('Raspberry Pi');
% cfg.InstructionSetExtensions = 'Neon v7';
% cfg.EnableOpenMP = true;
cfg.HardwareImplementation.ProdHWDeviceType = 'ARM Compatible->ARM Cortex-A';Step 3: Define Input Types and Generate
% Define input types matching your model
numFeatures = 10; % Match your feature count
inputType = coder.typeof(single(0), [1 numFeatures]);
% Generate code (network is loaded internally via coder.loadDeepLearningNetwork)
codegen -config cfg predictDLNet -args {inputType}Step 3b: Generate MEX First for Desktop Validation
Before generating a static library for the target, generate a MEX function to validate the pipeline on the desktop:
% Generate MEX for desktop testing
cfgMex = coder.config("mex");
codegen -config cfgMex predictDLNet -args {inputType}
% Compare MEX output to MATLAB output
yMATLAB = predictDLNet(xSample);
yMEX = predictDLNet_mex(xSample);
maxDiff = max(abs(yMATLAB - yMEX));
fprintf("Max MEX vs. MATLAB difference: %e\n", maxDiff);MEX validation catches code generation issues (unsupported operations, dimension mismatches) without requiring the target cross-compiler toolchain.
Step 4: Numerical Equivalency -- Generated Code vs. MATLAB/Simulink
After MEX generation, validate that the generated code produces numerically equivalent results to both the MATLAB compressed model and the Simulink model.
%% Numerical Equivalency: Full Pipeline Validation
% Compare: MATLAB compressed model vs MEX vs Simulink
numTests = 100; % As agreed with user
errMex = zeros(numTests, 1);
errSimulink = zeros(numTests, 1);
for i = 1:numTests
xTest = single(testInputs{i});
% MATLAB reference
yMatlab = predictDLNet(xTest);
% MEX output
yMex = predictDLNet_mex(xTest);
% Simulink output (if available from Phase 6)
ySimulink = simulinkOutputs(i, :);
errMex(i) = max(abs(yMatlab(:) - yMex(:)));
errSimulink(i) = max(abs(yMatlab(:) - ySimulink(:)));
end
fprintf('\nFull Pipeline Numerical Equivalency Report\n');
fprintf('============================================\n');
fprintf('Tests run: %d\n', numTests);
fprintf('MATLAB vs MEX -- MAE: %.4e, Max: %.4e\n', mean(errMex), max(errMex));
fprintf('MATLAB vs Simulink MAE: %.4e, Max: %.4e\n', mean(errSimulink), max(errSimulink));
if max(errMex) < 1e-5 && max(errSimulink) < 1e-4
fprintf('Pipeline status: PASS\n');
else
fprintf('Pipeline status: INVESTIGATE\n');
endThis validates the complete chain: original model → MATLAB import/rebuild → compression → Simulink → generated code. All stages must agree within expected tolerances.
Step 5: Review Generated Code (Optional)
If the user asks to review the generated code, open the code generation report:
% For MATLAB Coder:
rtw.report.open('predictDLNet', fullfile(pwd, 'codegen', 'lib', 'predictDLNet'));
% For Simulink/Embedded Coder:
rtw.report.open(modelName, fullfile(pwd, [modelName '_ert_rtw']));Target Support Packages
Embedded Coder support packages for specific hardware targets (e.g., Qualcomm
Hexagon, Infineon AURIX, STMicroelectronics STM32, NXP S32K) must be installed
separately. Check availability via matlabshared.supportpkg.getInstalled. If
the required package is missing, direct the user to the Add-On Explorer.
Hardware-Specific Configurations
ARM Cortex-M (Most Common for Pattern 1)
cfg.HardwareImplementation.ProdHWDeviceType = "ARM Compatible->ARM Cortex-M";
% NOTE: ProdBitPerChar/Short/Int/Long/Float/Double and ProdEndianess are
% auto-configured when ProdHWDeviceType is set to a known device.
% These are read-only in R2026a. Only set ProdHWDeviceType.ARM Cortex-A/R
cfg.HardwareImplementation.ProdHWDeviceType = "ARM Compatible->ARM Cortex-A";Texas Instruments C2000 (DSP)
cfg.HardwareImplementation.ProdHWDeviceType = "Texas Instruments->C2000";x86 (Desktop/Server with MKL-DNN)
cfg = coder.config('lib', 'ecoder', true);
cfg.TargetLang = 'C';
cfg.DeepLearningConfig = coder.DeepLearningConfig('mkldnn');GPU (NVIDIA — cuDNN or TensorRT)
% cuDNN
cfg = coder.config('lib', 'ecoder', true);
cfg.TargetLang = 'C++';
cfg.DeepLearningConfig = coder.DeepLearningConfig('cudnn');
% TensorRT (optimized inference)
cfg = coder.config('lib', 'ecoder', true);
cfg.TargetLang = 'C++';
cfg.DeepLearningConfig = coder.DeepLearningConfig('tensorrt');CMSIS/CMSIS-NN Optimization for ARM Cortex-M
Two paths exist for CMSIS acceleration on Cortex-M:
CMSIS-NN (INT8, Conv2D and FC only): Available via BOTH the Simulink CRL path (
slbuildwith ARM Cortex-M CRL) AND MATLAB Coder (coder.DeepLearningConfig('cmsis-nn')).CMSIS-DSP (float32 matrix-multiply for FC/LSTM/GRU/BiLSTM): Requires the Simulink CRL path only — not available through MATLAB Coder alone.
When the deployment target is an ARM Cortex-M processor (M0, M0+, M3, M4, M7, M33), enable CMSIS optimization for significant performance gains. Requires the Embedded Coder Support Package for ARM Cortex-M Processors (CMSIS library v5.9).
Supported Layers and Acceleration (R2026a)
Sources:
Supported Deep Learning Toolbox Blocks with CMSIS for ARM Cortex-M — Simulink block replacement (INT8 CMSIS-NN)
Code Generation for Matrix Multiplication in DL Layers with CMSIS — float32 mat-mult replacement (CMSIS-DSP)
| Layer | CMSIS-NN (INT8 Simulink block) | CMSIS-DSP (float32 mat-mult) |
|---|---|---|
convolution2dLayer | arm_convolve_wrapper_s8 | — |
fullyConnectedLayer | arm_fully_connected_s8 | mw_arm_mat_mult_f32 |
convolution1dLayer | — | — |
lstmLayer | — | mw_arm_mat_mult_f32 |
gruLayer | — | mw_arm_mat_mult_f32 |
bilstmLayer | — | mw_arm_mat_mult_f32 |
Key takeaways:
INT8 CMSIS-NN replacement is limited to Conv2D and FC. There is no INT8 kernel for LSTM/GRU/BiLSTM/Conv1D in R2026a. A quantized recurrent layer generates as plain fixed-point C, not an accelerated CMSIS kernel.
Float32 CMSIS-DSP replacement (
mw_arm_mat_mult_f32) covers FC, LSTM, GRU, BiLSTM. For recurrent-heavy networks where latency matters, the float32 path with CMSIS-DSP may outperform the quantized path (since no INT8 kernel exists for recurrent layers).
Scenario A: Simulink Path with CMSIS CRL (INT8 or float32)
This is the simplest approach — add one configuration line before slbuild:
% After exportNetworkToSimulink, before building:
set_param(modelName, 'SystemTargetFile', 'ert.tlc');
set_param(modelName, 'ProdHWDeviceType', 'ARM Compatible->ARM Cortex-M');
set_param(modelName, 'CodeReplacementLibrary', 'ARM Cortex-M');
slbuild(modelName);With quantized model: CMSIS-NN INT8 kernels replace Conv2D and FC blocks only (~2.8–3x speedup on those layers). Quantized LSTM/GRU/BiLSTM layers in the model generate as plain fixed-point C — no CMSIS replacement.
With float32 model: CMSIS-DSP
mw_arm_mat_mult_f32replaces matrix multiply in FC, LSTM, GRU, and BiLSTM layers.
Scenario B: MATLAB Coder Path with CMSIS-NN (no Simulink)
For CNN/FC-only models when Simulink is not available, use coder.DeepLearningConfig('cmsis-nn')
with a calibration results file for INT8 code generation:
cfg = coder.config('lib');
cfg.TargetLang = 'C';
cfg.Hardware = coder.hardware('ARM Cortex-M');
dlcfg = coder.DeepLearningConfig('cmsis-nn');
dlcfg.CalibrationResultFile = 'calibrationResults.mat';
cfg.DeepLearningConfig = dlcfg;
codegen -config cfg predictFcn -args {inputType}Covers Conv2D and FC layers with INT8 CMSIS-NN kernels
Does NOT provide CMSIS-DSP float32 replacement for LSTM/GRU — use the Simulink path (Scenario C) for recurrent models
Requires the "MATLAB Coder Interface for Deep Learning" support package
Scenario C: Simulink Path with CMSIS-DSP CRL (float32, LSTM/GRU focus)
For sequence models (LSTM/GRU) where INT8 quantization is not suitable (see dlquantizer layer support table in compression.md), use the CMSIS-DSP code replacement for float32 matrix operations:
% Export float32 network (unquantized)
exportNetworkToSimulink(net, ModelName="model_lstm", ...
Stateful=true, InputDataType="single", SampleTime="1");
% Enable CMSIS-DSP CRL — optimizes FC/LSTM/GRU matrix multiplications
set_param('model_lstm', 'SystemTargetFile', 'ert.tlc');
set_param('model_lstm', 'ProdHWDeviceType', 'ARM Compatible->ARM Cortex-M');
set_param('model_lstm', 'CodeReplacementLibrary', 'ARM Cortex-M');
slbuild('model_lstm');When to Use Each Scenario
Use compression-decision.md to pick the path. Quick
reference:
| Model Type | Goal | Has Simulink? | Recommended |
|---|---|---|---|
| CNN or FC-only model | Flash or latency | Yes | Scenario A with quantized model (INT8 CMSIS-NN, ~2.8–3x) |
| CNN or FC-only model | Flash or latency | No | Scenario B (MATLAB Coder CMSIS-NN, ~1.3x) |
| LSTM/GRU/BiLSTM model | Latency | Yes | Scenario C — keep float32, get CMSIS-DSP mw_arm_mat_mult_f32 |
| LSTM/GRU/BiLSTM model | Flash (retraining OK) | Yes | Project + quantize → Scenario A pattern. FC layers get CMSIS-NN INT8; recurrent layers generate as plain fixed-point C (no CMSIS speedup). |
| LSTM/GRU/BiLSTM model | Flash (no retraining) | Yes | Quantize → Scenario A pattern. Same caveat: only FC accelerated by CMSIS-NN. |
| LSTM/GRU model | Any goal | No | Generic C via MATLAB Coder (DeepLearningConfig('none')). CMSIS-DSP mw_arm_mat_mult_f32 requires the Simulink CRL path; without Simulink there is no CMSIS acceleration for recurrent layers. CMSIS-NN INT8 via DeepLearningConfig('cmsis-nn') only accelerates Conv2D/FC, not LSTM/GRU. |
PIL Verification with CMSIS
After generating CMSIS-optimized code, validate on actual hardware via PIL:
% For Simulink path: set simulation mode to PIL
set_param(modelName, 'SimulationMode', 'processor-in-the-loop');
simOut = sim(modelName);
% For MATLAB Coder path: generate PIL MEX
cfg.VerificationMode = 'PIL';
cfg.Hardware = coder.hardware('STM32F7xx Based'); % or your board
codegen -config cfg predict_cmsis -args {inputType}
% Compare PIL output to MATLAB output
yPIL = predict_cmsis_pil(xTest);
yMATLAB = predict(net, dlarray(single(xTest), 'BC')); % xTest is [1 x numFeatures]
maxErr = max(abs(yPIL(:) - extractdata(yMATLAB(:))));
fprintf('PIL vs MATLAB max error: %.4e\n', maxErr);Code Generation from Simulink
Configure the Model
% Open model
open_system("myModel");
% Set solver to fixed-step (required for code generation)
set_param("myModel", "SolverType", "Fixed-step");
set_param("myModel", "FixedStep", "0.001");
% Set system target file
% With Embedded Coder:
set_param("myModel", "SystemTargetFile", "ert.tlc");
% Without Embedded Coder (Simulink Coder only):
set_param("myModel", "SystemTargetFile", "grt.tlc");
% Configure hardware
cs = getActiveConfigSet("myModel");
switchTarget(cs, "ert.tlc", []);
set_param("myModel", "ProdHWDeviceType", "ARM Compatible->ARM Cortex-M");
Build the Model
% Build and generate code
slbuild("myModel");
% Or use the Embedded Coder app interactively
% embeddedCoderApp("myModel");Generated Code Structure
Generated code is placed in:
<modelName>_ert_rtw/(Embedded Coder)<modelName>_grt_rtw/(Simulink Coder)
Key files:
<modelName>.c-- Main model code and parameters<modelName>.h-- Model header<modelName>_types.h-- Type definitionsrtwtypes.h-- Common data types*.bin-- Weight data (whenLargeConstantThresholdis exceeded)
Code Size Estimation
Pre-Codegen Estimate (MATLAB)
Use analyzeNetwork to estimate parameter counts and memory before
generating code:
na = analyzeNetwork(net, Plots='none');
fprintf('Total learnables: %d\n', na.TotalLearnables);Post-Codegen Measurement (Compiled Binary)
After compiling with the target toolchain, use arm-none-eabi-size for accurate
flash/RAM measurements:
arm-none-eabi-size model.elfThe .text + .rodata sections give flash usage; .data + .bss give RAM usage.
Do NOT estimate weight sizes from generated .c source file sizes — C source text
overhead inflates the numbers significantly (e.g., 0.0234375F takes 10+ bytes in
source vs. 4 bytes as float32 binary). When LargeConstantThreshold = 0 is set,
weights are stored in .bin files rather than in .c source.
Post-Generation Verification
Software-in-the-Loop (SIL) Testing
% Run SIL test to compare MATLAB and generated code behavior
set_param("myModel", "CodeExecutionProfiling", "on");
set_param("myModel", "CodeProfilingInstrumentation", "on");
% Run SIL simulation
simOut = sim("myModel", "SimulationMode", "software-in-the-loop");Processor-in-the-Loop (PIL) Testing
% Requires target hardware connection
% Run PIL test to verify on actual target processor
simOut = sim("myModel", "SimulationMode", "processor-in-the-loop");Deployment Checklist
Before delivering generated code:
[ ] Code compiles without errors for target architecture
[ ] ROM usage within target flash capacity
[ ] RAM usage within target SRAM capacity
[ ] Inference time meets latency requirements
[ ] Numerical results match MATLAB simulation within acceptable tolerance
[ ] Full pipeline numerical equivalency validated (original model → MATLAB → Simulink → C)
[ ] SIL test passed (simulation vs. generated code agreement)
[ ] PIL test passed (if target hardware available)
[ ] No dynamic memory allocation in generated code (for safety-critical)
[ ] Code generation report reviewed (if user requested it)
[ ] Accuracy loss from compression explicitly documented
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.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-deploy-embedded-ai.zip