MATLAB logo, Simulink wordmark, colored surface graphic, modeling software illustration

Protect Simulink Design in MATLAB

2.5K Views
40
700
60
25
60
PCBWay

Hello friends! In this tutorial, we will learn how to share a Simulink design without distributing its editable implementation. You may have developed a controller, a signal-processing algorithm or a plant model that another person needs to simulate. The challenge is to give that person a usable component while keeping your original design private.

The original version of this tutorial used a generated S-function. We will keep that method, explain what it actually protects and then look at the protected-model workflow available in current Simulink releases. These approaches produce different deliverables, so the right choice depends on what the recipient needs to do.

If you are distributing MATLAB functions rather than Simulink models, see our tutorial on converting MATLAB M-files to P-files. P-code and protected Simulink models solve related problems, but you cannot protect an entire block diagram simply by running pcode on it.

MATLAB logo, Simulink wordmark, colored surface graphic, modeling software illustration
Figure: MATLAB and Simulink provide the software context for the model-protection tutorial.

What Does Protecting a Simulink Design Mean?

A normal Simulink model exposes blocks, connections and configuration details to anyone who receives the editable model and its dependencies. A subsystem groups blocks into a convenient unit, but grouping alone does not hide their implementation. A mask gives a subsystem a customized interface; it should not be treated as a security boundary.

For this tutorial, protection means distributing a component that the recipient can use through an agreed interface without receiving the original editable diagram. It does not mean that every detail about the design becomes unknowable. Input-output measurements can still reveal behavior, and interface descriptions necessarily disclose some information.

Keep three separate things in mind:

  • The source design: your editable model, initialization scripts, data and development history.
  • The delivered component: the protected model or compiled S-function that another project uses.
  • The interface contract: the signals, parameters, timing and operating limits that make the component usable.

You update the source design and rebuild the deliverable when the algorithm changes. Protection is not a reason to discard your source files or stop maintaining them.

Choose Between a Protected Model and an S-Function

ApproachTypical deliverableSuitable useMain consideration
Protected modelA .slxp file and required supporting filesSharing a referenced component with controlled capabilitiesThe author must enable the operations the recipient needs.
Generated S-functionA compiled MEX file, block and associated packageMaintaining an existing compiled-component workflowPlatform, build configuration and downstream code-generation needs affect the package.
Editable referenced modelA .slx model and dependenciesCollaborative development where recipients need to inspect and modify the designIt exposes the implementation.
Masked subsystemA subsystem with a custom dialogMaking configuration easier for usersA convenient interface does not itself provide implementation protection.

For a new protected Simulink component, start by evaluating protected models. MathWorks identifies protected models as a preferred intellectual-property protection workflow in its S-function deployment documentation. An S-function remains useful when an established project already depends on that delivery format.

Prepare a Clear Component Boundary

Before building either deliverable, decide which part of the model you are sharing. Packaging an entire test bench can accidentally include scopes, test inputs, confidential calibration data or dependencies that the recipient does not need.

Consider a discrete controller that receives a temperature error and produces a heater command. The test bench might contain a simulated oven, a reference-temperature generator and plots. The controller is the component; the oven and reference generator belong in a harness used to exercise it.

Interface itemExample definitionReason to document it
InputScalar temperature error in degrees Celsius, double precisionA temperature reading and a temperature error are not interchangeable.
OutputScalar heater duty command between 0 and 1The recipient must know whether 0.5 means 50% duty or another physical quantity.
Execution period0.01 sController behavior depends on its update rate.
Initial conditionIntegrator state starts at zeroStartup behavior should be reproducible.
Tunable parameterA documented proportional gain with a permitted rangeThe recipient needs to know which changes the component supports.
Exceptional inputA defined response to invalid sensor dataFault handling must be understood before integration.

This is an example contract, not a description of every controller. Write the actual definitions for your design. For a bus input, also provide the bus type and the meaning, dimensions and units of each element.

Why sample time matters

For an execution period Ts, the execution frequency is:

fs = 1 / Ts

With Ts = 0.01 s, the component executes at 100 Hz. Changing the period to 0.001 s gives 1000 Hz. That difference can alter a discrete controller's response and computational load.

For example, an explicit integrator might use I[k] = I[k-1] + KiTse[k]. The time interval appears directly in the calculation. A parent model cannot arbitrarily change a component's timing and assume equivalent behavior. Referenced models have specific sample-time inheritance requirements; confirm the applicable rules for your design.

Method 1: Create a Protected Simulink Model

Step 1: Keep a source copy and establish a working simulation

Save the editable model in your normal source project. Record the MATLAB release, required products, initialization procedure, solver settings and test inputs. Run the source model successfully before introducing protection, because a packaging operation does not repair an invalid model.

Use a small harness with representative inputs and logged outputs. For our controller example, useful cases include startup, a small positive error, a negative error and sustained saturation. These cases provide a practical basis for checking the delivered component later.

Step 2: Use a referenced model

Protected models are used through Model blocks. If the design currently sits inside a subsystem, convert that subsystem to a referenced model or reorganize it into a separate model with explicit ports.

In supported releases, select the subsystem and use the conversion command for a referenced model. The Model Reference Conversion Advisor checks the conversion and identifies required changes. Menu wording depends on the release. Follow the subsystem-to-referenced-model documentation rather than assuming an old screenshot matches your installation.

After conversion, confirm the parent model still simulates correctly. Pay attention to initialization, variable scope, signal dimensions and state ownership. A successful conversion command is useful, but the resulting component must still represent the intended system.

Step 3: Select the required capabilities

For simulation-only sharing, enable simulation and leave unrelated capabilities disabled. If a recipient must generate code from the parent model, the protected component needs compatible code-generation support. Allowing a read-only view is a separate decision because it reveals model contents.

Current releases provide a Protected Model Creator interface. You can open the protection workflow from a selected Model block. Creating protected models requires the relevant authoring products; simulation protection commonly uses Simulink Coder, while other capabilities have their own requirements. Check the Protected Model Creator documentation for your release and selected capabilities.

Do not enable every option just because it is available. Write down whether your recipient needs simulation, code generation or inspection, then configure those requirements explicitly.

Step 4: Generate the protected deliverable

For a model named controllerCore, the following illustrates the current programmatic workflow:

load_system('controllerCore');
Simulink.ModelReference.protect('controllerCore', ...
    'Mode', 'Simulation', ...
    'Project', true, ...
    'Report', true);

This example assumes the model is already configured for supported model-reference simulation. The protection operation creates a .slxp deliverable; requesting a project also packages supporting material. Options and supported modes vary across releases, so consult the installed help for Simulink.ModelReference.protect before adapting the command to an older installation.

The source model remains the editable master. Store generated deliveries separately and give each release a version identifier so that you can associate a delivered component with its source revision.

Step 5: Review passwords and supporting files

Where supported, passwords can restrict access to selected capabilities. Decide who should receive each password and deliver it through an appropriate channel. A password placed beside the package in an openly shared document provides little practical access control.

Inspect the package contents before distribution. Supporting data files can disclose calibration values or other information even when the block implementation is protected. Only include what the recipient needs, and do not assume that placing a file inside a project archive encrypts it.

Step 6: Use the component in a recipient-style harness

Place the protected component and its approved dependencies in a separate test project. Reference it with a Model block and provide the documented inputs and parameters. If access is password-controlled, use the supported authorization workflow.

A subtle issue arises when editable and protected versions with the same name are both available: model resolution can select the protected version when the reference omits the extension. Make your source-comparison setup explicit and inspect which artifact each harness uses. MathWorks explains these details in using a protected model in simulation.

Method 2: Generate an S-Function from a Subsystem

The original tutorial used a menu named Real-Time Workshop, followed by Generate S-Function. That wording belongs to older releases. Current versions organize these tools differently, and a historical instruction to select “Use Embedded Coder” should not be treated as a universal requirement.

  1. Keep the editable model and create a subsystem containing the component you want to package.
  2. Expose a clear interface using input and output ports. Remove test sources and scopes that do not belong in the component.
  3. Confirm that the component is supported by the S-function target and that an appropriate compiler is configured.
  4. Open the S-function generation workflow supported by your release. The S-function system target file is rtwsfcn.tlc.
  5. Identify any parameters that must remain tunable. Values compiled into the generated implementation cannot automatically become editable dialog parameters.
  6. Build the S-function and place the generated block in a test model.
  7. Compare its behavior with the source subsystem using the same inputs, timing and initial conditions.

A generated S-function can require particular input attributes and compatible solver settings. Read the Generated S-Function block documentation when configuring the receiving model.

Understand what you are distributing

For simulation, a compiled MEX binary may be the central deliverable; on supported 64-bit Windows systems, its extension is typically .mexw64. A binary built for one platform is not a universal executable for every operating system.

Downstream code generation changes the situation. The recipient may need generated source, headers and build folders in addition to the MEX binary. Those files may expose implementation details. Review the complete package against your protection objective instead of judging it only by whether double-clicking the block opens the original diagram.

The S-function target also has limitations, including restrictions involving Model blocks. If your component already contains referenced models, check target support before reorganizing the design around this method.

Check the Behavior of the Delivered Component

A protected component should preserve the promised behavior, not merely build without an error. Compare results with the source using identical inputs and consistent settings.

For sampled scalar outputs, a useful error measure is:

Emax = max |ydelivered[k] - ysource[k]|

Suppose the source produces 0.25, 0.50, 0.75 and the delivered component produces 0.25, 0.500001, 0.75. The maximum absolute difference is 0.000001. Whether that is acceptable depends on the signal's units, the numeric type and your engineering requirements.

Compare discrete status signals exactly when appropriate. For floating-point signals, choose justified absolute and relative tolerances. Do not compare array positions blindly if the simulations produce different time grids; first establish a valid time alignment.

  • Check startup and state reset behavior.
  • Exercise valid minimum and maximum input values.
  • Test supported parameter changes.
  • Check saturation, switching and fault conditions relevant to the model.
  • Run from a clean recipient-style project without the private source directory on the path.

These are suggested checks for your project; no particular model has been measured by the examples in this tutorial.

Common Problems and Practical Fixes

ProblemWhat to inspect
The component cannot be found.Check the MATLAB path, artifact name and Model block reference.
Simulation requests a missing variable.Check initialization scripts, data dictionaries and documented workspace dependencies.
The source and delivered outputs differ.Compare sample times, solver settings, parameters, initial states and input data.
The recipient cannot generate code.Check whether code generation was enabled and whether the supplied targets and build artifacts match the intended workflow.
A compiled S-function fails to load.Check platform compatibility and required binary dependencies.
The component runs an older algorithm.Rebuild after source changes and inspect path resolution for stale copies.
The package exposes confidential data.Review supporting files as well as the protected implementation.

Release compatibility is capability-dependent. Record the authoring release and confirm the receiving environment against the relevant documentation. Do not assume that a protected file or MEX binary supports every earlier or later MATLAB release.

Review: A Maintainable Protection Workflow

Start with a working source model, define a small interface and choose the delivery format around the recipient's needs. Build the component, compare its behavior with the source and package only the necessary supporting files. Keep the editable source private and reproducible so that future fixes can produce a new delivery.

The protected-model approach usually provides the clearest capability controls for a new Simulink delivery. The original S-function approach can still fit an existing workflow, provided you account for its build requirements and the information exposed by any accompanying source files.

Frequently Asked Questions

Does creating a subsystem protect my design?

No. A subsystem organizes the diagram. A recipient with the editable model can normally inspect its contents. Use an appropriate protected or compiled delivery when you need to withhold the implementation.

Can I edit my design after generating a protected model?

Yes, you edit your retained source model and generate a new protected version. The protected deliverable is not a replacement for the source project.

Does the recipient need the same products as the author?

Requirements depend on the enabled capabilities and supporting components. Creating a protected model and using one are different activities; document the recipient's actual simulation or code-generation requirements.

Can I hide the diagram while allowing parameter tuning?

Yes, when the selected delivery workflow supports the required tunable interface. Expose only the intended parameters and document their types, units and limits. Test tuning with the delivered artifact.

Is a generated S-function completely impossible to analyze?

No such guarantee should be made. A compiled component can withhold the original diagram, but observable behavior and distributed build files still reveal information.

Should I send the original SLX file with the protected model?

Only if you intend to share the editable implementation. For a protected delivery, keep the original source in your development project and send the approved artifact, dependencies and interface documentation.


Comments

1

Join the conversation

Reply1

This protects your model against editing, but not from viewing. The C code is still visible in the generated files if you need to do code generation... and it isn't too hard to figure out the IP from the C code.