Matlab Deploy AI Model
MathWorksOfficialCreated by MathWorks
- Skill
- Tool integration
- Software development
- BSD-2-Clause
- Low risk
From the skill’s files
Taken from the skill’s own files (its description, section headings and stated usage). Not an AutoGineer summary, and not written by the author as one.
Generate C/C++ or CUDA code from an AI model (PyTorch, LiteRT) using MATLAB Coder or GPU Coder. Use when the user wants to integrate an AI model into an application with code generation as the end goal — generating MEX, CUDA MEX, static library, dynamic library, or executable — or using the model in Simulink for simulation and code generation. Covers PyTorch ExportedProgram (.pt2) via loadPyTorchExportedProgram and LiteRT (.tflite) via loadLiteRTModel (R2026a+). Keywords: PyTorch, torch, .pt2, ExportedProgram, loadPyTorchExportedProgram, invoke, codegen, MEX, CUDA, GPU, C, C++, deploy, AI model, deep learning model, LiteRT, TFLite, TensorFlow Lite, Simulink, slbuild, PyTorch ExportedProgram block, MATLAB Function block, dlosslib, loadLiteRTModel. Generate deployable C/C++ or CUDA code from an AI model using MATLAB Coder or GPU Coder. The workflow follows a common pattern regardless of…
What it does
- When to Use
- When NOT to Use
- Supported Frameworks
- Generic Workflow
- Key Functions
- Conventions
When to use it
- Use when the user wants to integrate an AI model into an application with code generation as the end goal — generating MEX, CUDA MEX, static library, dynamic library, or executable — or using the…
- User wants to generate C/C++/CUDA code from an AI model (PyTorch, LiteRT)
- User has a model file (.pt2, .tflite) and wants to load it into MATLAB
- User wants MEX acceleration for an AI model
- User wants to generate CUDA code or GPU-accelerated MEX from an AI model
- User wants to deploy an AI model to hardware
Advantages
The skill’s files do not state this.
Usage examples
The skill’s files do not state this.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/matlab/matlab-deploy-ai-model/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip matlab-deploy-ai-model.zip -d .agents/skills
Documentation by MathWorks
Generate C/C++/CUDA Code from an AI Model
Generate deployable C/C++ or CUDA code from an AI model using MATLAB Coder or GPU Coder. The workflow follows a common pattern regardless of model framework: load, inspect, write entry-point, generate MEX, verify, then generate production code.
When to Use
User wants to generate C/C++/CUDA code from an AI model (PyTorch, LiteRT)
User has a model file (.pt2, .tflite) and wants to load it into MATLAB
User wants MEX acceleration for an AI model
User wants to generate CUDA code or GPU-accelerated MEX from an AI model
User wants to deploy an AI model to hardware
User wants to use a PyTorch or LiteRT model in Simulink (simulation or code generation)
User wants to verify AI model numerics between the source framework and MATLAB
When NOT to Use
General MATLAB Coder usage (codegen syntax, config tuning, writing codegen-ready code)
Editable dlnetwork for Deep Learning Toolbox workflows (quantization, compression, transfer learning) — use
importNetworkFromPyTorch(PyTorch),importNetworkFromTensorFlow(SavedModel), orimportNetworkFromKeras(.keras/.h5) which return adlnetwork. For deployment of an editabledlnetworkwith model compression (INT8 quantization viadlquantizer, pruning, projection) orexportNetworkToSimulinkworkflows — usematlab-deploy-embedded-ai(Pattern 1).Training or fine-tuning — this skill is for inference code generation only
Supported Frameworks
| Framework | Model format | Load function | Status |
|---|---|---|---|
| PyTorch | .pt2 | loadPyTorchExportedProgram | Supported (R2026a+) |
| LiteRT / TFLite | .tflite | loadLiteRTModel | Supported (R2026a+) |
For PyTorch-specific details (API routing, entry-point pattern, export workflow,
data layout, common mistakes): see references/pytorch-workflow.md.
For LiteRT-specific details (API routing, entry-point pattern, variable-size inputs,
Simulink integration, conventions): see references/litert-workflow.md.
For converting TensorFlow/Keras/.h5 to .tflite: see
references/tensorflow-to-litert-conversion.md.
Generic Workflow
The code generation workflow follows the same steps for any framework:
1. Load and Inspect
Load the model and check its input/output specifications to determine expected shapes and types.
2. Write Entry-Point Function
Create a codegen-compatible entry-point function that:
Loads the model from a file path
Runs inference on an input
Returns the output
The model file path must be wrapped with coder.Constant so it's known at
compile time.
3. Verify Numerics
Compare MATLAB inference output against the source framework to confirm correct loading. Use the same input data in both environments and compare with tolerance.
4. Generate MEX (First!)
Always generate MEX before lib/exe to verify on the host machine:
CPU MEX:
cfg = coder.config("mex");
codegen -config cfg -args {coder.Constant("model_file"), input} entryPointCUDA MEX (GPU acceleration):
cfg = coder.gpuConfig("mex");
codegen -config cfg -args {coder.Constant("model_file"), input} entryPointFor CPU MEX SIMD acceleration (SIMDAcceleration = 'Full' for AVX2 on
Intel/AMD), see the matlab-generate-code skill. For the DNN-
inference-specific MEX AVX2 ceiling, see references/dnn-codegen-options.md.
5. Verify MEX Output
Compare MEX output against MATLAB reference using matlab.unittest with
tolerance:
refOut = entryPoint("model_file", input);
mexOut = entryPoint_mex("model_file", input);
testCase = matlab.unittest.TestCase.forInteractiveUse;
testCase.verifyThat(mexOut, matlab.unittest.constraints.IsEqualTo(refOut, ...
'Within', matlab.unittest.constraints.AbsoluteTolerance(single(1e-5))));6. Generate Library/Executable
Once MEX is verified, generate production code:
cfgLib = coder.config("lib");
cfgLib.TargetLang = "C++"; % set to "C++" for C++ output; default is "C"
codegen -config cfgLib -args {coder.Constant("model_file"), input} entryPointFor DLL: coder.config("dll"). For executable: coder.config("exe").
CUDA variants: Replace coder.config with coder.gpuConfig.
Performance tuning:
Generic knobs (SIMD instruction sets, reduction-loop vectorization, multithreaded loops): see the
matlab-generate-codeskill.MATLAB Coder ↔ Simulink Coder property naming duality and
slbuildset_parampatterns: see thematlab-deploy-embedded-codeskill.DNN-inference-specific knobs (
DLTargetLibrary/DeepLearningConfigto disable third-party DL libraries,LargeConstantGenerationto serialize weights to data files): seereferences/dnn-codegen-options.md.
7. Use in Simulink
For Simulink integration, use the dedicated PyTorch ExportedProgram block from
dlosslib — set ModelFilePath to the .pt2 file and it auto-detects
input/output shapes. No entry-point function or coder.Constant needed.
Pre/post-processing can be done with Simulink blocks around the dedicated block.
If you need everything in a single block, use a MATLAB Function block with
loadPyTorchExportedProgram + invoke (same pattern as the entry-point, but
the model path is a string literal — no coder.Constant).
Both paths support slbuild code generation (requires fixed-step solver + ERT
or GRT target). See references/simulink-workflow.md for full details.
8. Deploy to Hardware (Optional — requires Embedded Coder)
For embedded deployment, use the same entry-point function with an Embedded Coder
configuration. See the matlab-deploy-embedded-code skill for ERT config,
hardware settings, PIL/SIL verification, and target-specific options.
Ask the user to install the skill if it is not installed
Key Functions
| Function | Purpose | Package | Since |
|---|---|---|---|
coder.Constant | Make argument a compile-time constant | MATLAB Coder | R2011a |
coder.gpuConfig | Create GPU (CUDA) code generation config | GPU Coder | R2017b |
codegen | Generate code | MATLAB Coder | R2011a |
loadPyTorchExportedProgram | Load .pt2 into MATLAB | MATLAB Coder Support Package for PyTorch and LiteRT Models | R2026a |
loadLiteRTModel | Load .tflite into MATLAB | MATLAB Coder Support Package for PyTorch and LiteRT Models | R2026a |
Conventions
Always check the model's input specifications for correct input shape and type
Always generate MEX first, verify, then proceed to lib/exe
Always use
coder.Constantfor the model file path argumentInput data is typically single-precision (check model input specs to confirm)
Do NOT use
importNetworkFromPyTorch,importNetworkFromTensorFlow, orimportNetworkFromKerasin this skill — they return adlnetworkon a different path. If the user needs adlnetworkfor quantization, projection, pruning, orexportNetworkToSimulinkbefore code generation, route tomatlab-deploy-embedded-aiinstead
References
references/pytorch-workflow.md— Full PyTorch-specific workflow: API routing, entry-point pattern, export guidance, common mistakes, and conventions. Consult for any PyTorch/.pt2 model code generation task. Links to deeper PyTorch references (API signatures, data layout, numeric verification, supported models).references/export-pytorch-models.md— Exporting an eager-mode PyTorch model to.pt2withtorch.export(upstream of loading). Consult when the user has a PyTorch model but no.pt2file yet, or hitstorch.exportSerializeError/ kwarg-mismatch errors. Links topytorch-export-patterns.md(per-source templates) andpytorch-export-gotchas.md(torch 2.11 serialization fixes).references/simulink-workflow.md— Simulink integration: dedicated PyTorch ExportedProgram block (Path A) vs MATLAB Function block (Path B), block mask parameters, code generation config, and key differences from command-line codegen.references/litert-workflow.md— Full LiteRT-specific workflow: API routing (loadLiteRTModel→inputSpecifications→invoke), entry-point pattern, variable-size input handling, Simulink integration, and conventions. Consult for any LiteRT/.tflite model code generation task.references/tensorflow-to-litert-conversion.md— Converting TensorFlow SavedModel/Keras/.h5 to.tflitevia the Pythontf.lite.TFLiteConverterAPI. Consult when the user has a TensorFlow model but no.tflitefile yet.references/litert-numeric-verification.md— Verifying MEX numerics against MATLAB reference for LiteRT models (tolerance guidance, common mismatches).references/codegen-workflow.md— Shared code generation steps for both PyTorch and LiteRT: MEX generation, MEX verification, library/executable targets,coder.Constantusage, andcoder.DeepLearningConfignotes.references/dnn-codegen-options.md— DNN-INFERENCE-SPECIFIC codegen options:DLTargetLibrary/DeepLearningConfig('none')for the plain-C DL path,LargeConstantGenerationfor serializing large DNN weights to data files, and MEX SIMD ceiling in a DNN-inference context. Read this when the generic file's knobs need DNN-specific framing (e.g., "the MEX SIMD cap matters because inference is the target").
See Also
matlab-generate-code— Generic MATLAB Coder tuning (SIMD instruction sets, OpenMP multi-threading, reduction-loop vectorization). Consult for performance options not specific to DNN inference.matlab-deploy-embedded-ai—dlnetwork-based codegen with model compression (quantization, pruning, projection) andexportNetworkToSimulinkworkflows (Pattern 1). Use it when the source is an editabledlnetworkin MATLAB rather than a.pt2/.tflitefile.matlab-optimize-gpu-codegen— CUDA-target codegen tuning (coder.gpuConfig, kernel fusion, memory-hierarchy options) when the deployment target is an NVIDIA GPU rather than CPU or embedded hardware.
Copyright 2026 The MathWorks, Inc.
Files
- ATTRIBUTION.mdAdded by AutoGineer1.0 KiB
- LICENSELicence file added by AutoGineer1.4 KiB
- SKILL.md10.8 KiB
- manifest.yaml617 B
- references/codegen-workflow.md4.0 KiB
- references/dnn-codegen-options.md6.9 KiB
- references/export-pytorch-models.md4.6 KiB
- references/litert-numeric-verification.md3.8 KiB
- references/litert-workflow.md14.7 KiB
- references/pytorch-api-reference.md2.6 KiB
- references/pytorch-data-layout.md4.1 KiB
- references/pytorch-export-gotchas.md4.7 KiB
- references/pytorch-export-patterns.md5.2 KiB
- references/pytorch-numeric-verification.md2.6 KiB
- references/pytorch-supported-models.md3.4 KiB
- references/pytorch-workflow.md5.7 KiB
- references/simulink-workflow.md12.7 KiB
- references/tensorflow-to-litert-conversion.md5.8 KiB
references/litert-workflow.md
Generate C/C++/CUDA Code from a LiteRT Model
Complete workflow for generating C/C++ or CUDA code from a LiteRT model (.tflite) using the MATLAB Coder Support Package for PyTorch and LiteRT Models (R2026a+).
Critical: API Routing
Three different pipelines exist for .tflite models. Choose based on the goal:
| Deep Learning Toolbox path (editable dlnetwork) | MATLAB Coder Support Package for PyTorch and LiteRT Models (code generation) | LiteRT Interpreter path (bit-true on-target) | |
|---|---|---|---|
| Load | importNetworkFromTensorFlow | loadLiteRTModel | loadTFLiteModel |
| Object | dlnetwork | LiteRTModel | TFLiteModel |
| Inference | predict(net, dlarray(...)) | invoke(model, input) | predict(model, input) |
| Codegen | coder.loadDeepLearningNetwork + DeepLearningConfig | Entry-point calls loadLiteRTModel + invoke | Generates code that calls LiteRT C++ API at runtime |
| Data layout (2-D images) | HWCN (MATLAB convention) | NHWC (LiteRT convention preserved) | HWCN |
| Since | R2022b | R2026a | R2024a |
| Use for | Transfer learning, compression (DLT tools) | Standalone C/C++/CUDA code generation | Bit-true inference via LiteRT interpreter on-target |
| Limitations | Converts model to dlnetwork; no support for quantized tensorflow models | — | No standalone C/CUDA — requires LiteRT runtime on target; must be built on target HW; not supported on macOS |
Rule: If the goal is to keep the model's source of truth in TensorFlow/LiteRT
and generate standalone C/C++/CUDA code from it, use the MATLAB Coder Support
Package for PyTorch and LiteRT Models path (loadLiteRTModel + invoke). Do not
use importNetworkFromTensorFlow, importNetworkFromKeras,
coder.loadDeepLearningNetwork, or dlarray on this path — those convert the
model to a dlnetwork first. If the user needs quantization (dlquantizer),
projection, pruning, or exportNetworkToSimulink and is OK with translating the
model to a dlnetwork using the Deep Learning Toolbox, then route to the
matlab-deploy-embedded-ai skill (Pattern 1), which covers dlnetwork-based
workflows.
loadTFLiteModel path: Use when the goal is bit-true inference that matches
the LiteRT interpreter exactly on the target hardware. The generated code calls
the LiteRT C++ API at runtime rather than producing standalone C/C++/CUDA — so the
LiteRT runtime library must be present on the target and the code must be built
on (or cross-compiled for) the target hardware. This path is not supported on
macOS. Choose loadLiteRTModel instead when you need portable standalone code
generation.
Obtaining a .tflite Model
LiteRT models (.tflite files) can originate from multiple frameworks:
From TensorFlow/Keras: Convert using tf.lite.TFLiteConverter in Python.
See references/tensorflow-to-litert-conversion.md for complete workflows
covering SavedModel, .keras, and legacy .h5 formats.
From PyTorch: Convert using litert_torch — a Google AI Edge workflow for
converting PyTorch models directly to LiteRT format without going through
TensorFlow. This is also a fallback route if loadPyTorchExportedProgram fails
due to unsupported operations — convert the model to .tflite via litert_torch
and use loadLiteRTModel instead.
Note (R2026a): After converting with litert_torch, the resulting .tflite
file may contain keep_stablehlo_constant metadata that prevents
loadLiteRTModel from loading it. Strip this metadata before use in MATLAB:
from ai_edge_litert import schema_py_generated as schema
import flatbuffers
with open(tflite_path, "rb") as f:
buf = f.read()
model = schema.ModelT.InitFromPackedBuf(buf, 0)
model.metadata = [
m for m in model.metadata
if (m.name.decode() if isinstance(m.name, bytes) else m.name)
!= "keep_stablehlo_constant"
]
builder = flatbuffers.Builder(len(buf) + 1024)
packed = model.Pack(builder)
builder.Finish(packed, b"TFL3")
with open(tflite_path, "wb") as f:
f.write(bytes(builder.Output()))This requires the ai_edge_litert and flatbuffers pip packages.
From JAX: JAX models can also be converted to .tflite format. This workflow
will be covered in a future skill update.
Workaround: Stateful Models (R2026a)
loadLiteRTModel does not support models with stateful operations (e.g.,
stateful LSTM/GRU). Loading such a model produces:
Models containing 'stateful' operations or tfl.assign_variable, tfl.call_once, tfl.read_variable, tfl.var_handle operations are not supported.
Workaround: Rewrite the model in Python to be stateless by passing hidden and cell states as explicit inputs/outputs, then emulate stateful behavior in MATLAB by feeding states back in a loop.
Step 1 — Rewrite the model in Python:
import tensorflow as tf
# Original (fails): stateful=True stores state internally
# model = tf.keras.Sequential([
# tf.keras.layers.LSTM(16, stateful=True, batch_input_shape=(1, 5, 3)),
# tf.keras.layers.Dense(2)
# ])
# Workaround: stateful=False, pass states explicitly, unroll for tflite
input_seq = tf.keras.Input(batch_shape=(1, 5, 3), name='input_seq')
h_in = tf.keras.Input(batch_shape=(1, 16), name='h_in')
c_in = tf.keras.Input(batch_shape=(1, 16), name='c_in')
lstm_out, h_out, c_out = tf.keras.layers.LSTM(
16, stateful=False, return_state=True, unroll=True
)(input_seq, initial_state=[h_in, c_in])
prediction = tf.keras.layers.Dense(2, name='prediction')(lstm_out)
model = tf.keras.Model(
inputs=[input_seq, h_in, c_in],
outputs=[prediction, h_out, c_out]
)
# Convert to tflite
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
with open('stateless_lstm.tflite', 'wb') as f:
f.write(tflite_model)Key changes:
stateful=False— no internal state variablesreturn_state=True— outputs h and c explicitlyunroll=True— required for tflite conversion (avoids TensorListReserve ops)States passed as explicit
Inputlayers
Step 2 — Emulate stateful inference in MATLAB:
model = loadLiteRTModel('stateless_lstm.tflite');
% Initialize states to zero
h = zeros(1, 16, 'single');
c = zeros(1, 16, 'single');
% Process sequence of inputs, carrying state forward
for step = 1:numSteps
input_seq = getNextInput(); % [1 5 3] single
[pred, h, c] = invoke(model, input_seq, h, c);
endStep 3 — Codegen entry-point:
function [pred, h_out, c_out] = statefulStep(modelPath, input_seq, h_in, c_in) %#codegen
model = loadLiteRTModel(modelPath);
[pred, h_out, c_out] = invoke(model, input_seq, h_in, c_in);
endThe caller maintains state between calls — the generated code itself is stateless. This pattern works for any RNN (LSTM, GRU) that was originally stateful.
Load and Inspect
model = loadLiteRTModel("model.tflite");
summary(model)
inSpecs = model.inputSpecifications;
outSpecs = model.outputSpecifications;Use inputSpecifications to determine the expected input shape and type.
LiteRT models preserve NHWC layout (batch, height, width, channels).
Variable-size batch dimension: Models converted from TensorFlow often have
Inf as the first dimension (variable-size batch). Three options exist for
codegen:
| Option | When to use | Example |
|---|---|---|
| Fixed batch | Known batch size at deployment | input = ones(1, 224, 224, 3, 'single') |
| Unbounded variable | Batch varies with no upper limit (requires DMA) | coder.typeof(single(0), [Inf 224 224 3], [1 0 0 0]) |
| Bounded variable | Batch varies up to a maximum (stack-allocates) | coder.typeof(single(0), [8 224 224 3], [1 0 0 0]) |
For the general concept of bounded/unbounded variable-size inputs with
coder.typeof, see the matlab-generate-code skill. Below is the
LiteRT-specific application:
% Fixed batch
input = ones(1, 224, 224, 3, 'single');
codegen -config cfg -args {coder.Constant("model.tflite"), input} mInvoke
% Unbounded variable batch
inputCT = coder.typeof(single(0), [Inf 224 224 3], [1 0 0 0]);
codegen -config cfg -args {coder.Constant("model.tflite"), inputCT} mInvoke
% Bounded variable batch (max 8)
inputCT = coder.typeof(single(0), [8 224 224 3], [1 0 0 0]);
codegen -config cfg -args {coder.Constant("model.tflite"), inputCT} mInvokeMulti-signature models: A LiteRT model can contain multiple functions
(signatures). Use FcnNames to discover them and FcnName to target one:
model = loadLiteRTModel("multi_sig.tflite");
model.FcnNames % e.g. ["adder", "multiplier"]
% Inspect a specific function's I/O
summary(model, FcnName="adder")
inSpecs = inputSpecifications(model, FcnName="adder");
% Invoke a specific function
out = invoke(model, in, FcnName="adder");If the model contains multiple functions, you must specify FcnName when
calling invoke, inputSpecifications, outputSpecifications, or summary.
Single-signature models have FcnNames = {'main'} — you do not need to pass
FcnName for these; invoke(model, input) works directly.
Entry-point for multi-signature codegen:
function out = mInvokeAdder(modelPath, input) %#codegen
model = loadLiteRTModel(modelPath);
out = invoke(model, input, FcnName="adder");
endExecutionMode: Controls how the LiteRTModel executes inference in MATLAB.
Options are "JIT" (default — just-in-time compiled) and "MEX" (compiles a
MEX for faster repeated inference in MATLAB). This is a MATLAB-side execution
setting and is separate from generating a MEX via codegen for deployment.
model = loadLiteRTModel("model.tflite", ExecutionMode="MEX");
model = loadLiteRTModel("model.tflite", ExecutionMode="JIT");Entry-Point Pattern
The standard entry-point for LiteRT model codegen:
function out = mInvoke(modelPath, input) %#codegen
model = loadLiteRTModel(modelPath);
out = invoke(model, input);
endEntry-point for multi-signature codegen:
function out = mInvokeAdder(modelPath, input) %#codegen
model = loadLiteRTModel(modelPath);
out = invoke(model, input, FcnName="adder");
endCode Generation (MEX, Library, Executable)
For the full codegen workflow (MEX generation, verification, library/executable
targets, coder.Constant usage, and coder.DeepLearningConfig notes), see
codegen-workflow.md.
Quick reference — CPU MEX:
cfg = coder.config("mex");
input = ones(1, 224, 224, 3, "single"); % NHWC — match inputSpecifications
codegen -config cfg -args {coder.Constant("model.tflite"), input} mInvokeCommon Mistakes
| Mistake | Why It's Wrong | Correct Approach |
|---|---|---|
importNetworkFromTensorFlow("model") | Returns dlnetwork (DLT path), cannot use invoke | loadLiteRTModel("model.tflite") |
importNetworkFromKeras("model.keras") | Returns dlnetwork (DLT path), unrelated to LiteRT codegen | Convert to .tflite first, then loadLiteRTModel |
loadTFLiteModel(...) for standalone codegen | Generates code that calls LiteRT C API at runtime — not standalone C/CUDA | loadLiteRTModel("model.tflite") for standalone code generation |
predict(model, input) | Wrong inference function for LiteRTModel | invoke(model, input) |
classify(model, input) | Wrong inference function for LiteRTModel | invoke(model, input) |
coder.loadDeepLearningNetwork(...) | DLT codegen API, not compatible with LiteRTModel | Use loadLiteRTModel in the entry-point directly |
coder.DeepLearningConfig('tensorrt') | Ignored by the MATLAB Coder Support Package path | Optional — has no effect on LiteRTModel codegen |
Input shape [224, 224, 3] (HWC) from imread | LiteRTModel expects NHWC with batch dim | Use [1, 224, 224, 3] (check inputSpecifications) |
Input shape [1, 3, 224, 224] (NCHW) | That's PyTorch convention, not LiteRT | LiteRT uses NHWC: [1, 224, 224, 3] |
| Passing LiteRTModel object to codegen | Rare pattern, not recommended | Pass model path as coder.Constant string |
Confusing ExecutionMode with codegen MEX target | ExecutionMode controls in-MATLAB execution, not code generation | Use coder.config("mex") + codegen for the MEX-first verification workflow |
Omitting coder.Constant for model path | Codegen needs model path at compile time | Always wrap model path: coder.Constant("model.tflite") |
Calling invoke without FcnName on a multi-signature model | Error — must specify which function to invoke | invoke(model, input, FcnName="adder") |
Conventions
Always use
loadLiteRTModelfor.tflitecode generation workflowsLiteRT models use NHWC layout — do not confuse with PyTorch's NCHW
For multi-signature models, always specify
FcnNameininvokeDo NOT use
importNetworkFromTensorFlow,importNetworkFromKeras,coder.loadDeepLearningNetwork,dlarray,predict, orclassifyon this skill's.tflitecodegen path. If the user needs adlnetworkfor quantization/projection/pruning orexportNetworkToSimulinkprior to codegen, route to thematlab-deploy-embedded-aiskillDo NOT use
loadTFLiteModelon this path — it produces code that calls the LiteRT C API at runtime (bit-true interpreter path), not standalone C/CUDA. UseloadLiteRTModelfor standalone code generationFor shared conventions (MEX-first,
coder.Constant, verify before lib), seecodegen-workflow.md
Use in Simulink
The dlosslib library provides a dedicated LiteRT block for .tflite models.
Usage is identical to the PyTorch ExportedProgram block:
modelName = "my_litert_model";
new_system(modelName);
add_block("dlosslib/LiteRT", [modelName "/MyModel"]);
set_param([modelName "/MyModel"], "ModelFilePath", "/path/to/model.tflite");The block auto-detects input/output shapes from the .tflite file.
Multi-signature models in Simulink: For .tflite models with multiple
functions, the LiteRT block provides a FcnName drop-down parameter to
select which function to invoke. Set it programmatically with:
set_param([modelName "/MyModel"], "FcnName", "detect");For full Simulink integration details (simulation modes, code generation config,
MATLAB Function block alternative), see simulink-workflow.md.
Detailed References
codegen-workflow.md— Shared codegen steps: MEX generation, verification, library/executable targets,coder.Constant,coder.DeepLearningConfig.litert-numeric-verification.md— pyrun-based pattern for comparing Python LiteRT Interpreter vs MATLAB outputs.simulink-workflow.md— Simulink integration for both PyTorch and LiteRT models (dedicated blocks, MATLAB Function block path, code generation config)."Generate CUDA Code for YOLO v11 (LiteRT)" (MATLAB documentation) — End-to-end example with preprocessing, postprocessing (NMS), and GPU Coder CUDA code generation from a LiteRT object detection model.
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.
Security
What our scanner noticed· Low risk
- Instructions that use the network
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/code-generation/matlab-deploy-ai-model · 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-ai-model.zip