How can I load a final state of a Simscape model in generated code?
Show older comments
Hi!
I have a Simscape model of which I generate code for deployment. This works great if I start the simulation at defined simple start conditions. However we want to run a simulation for some time to bring it into specific situations and safe these states as initial states for later simulations.
This functionality does already exist within Simulink via model settings (Save: "Data Import/Export" -> "Save to warkspace of file" -> "Final states:" // Load: "Data Import/Export" -> "Load from workspace" -> "Initial state:").
How do I achieve this for saving in Simulink and loading in generated code?
Accepted Answer
More Answers (1)
Vidhi Agarwal
on 8 Jul 2025
0 votes
You can try below given ways to implement to transfer the desired initial state from simulation into the deployed (generated) code:
- Block Parameters: Set the initial conditions directly in the relevant Simulink or Simscape block parameters, such as "Initial position" or "Initial velocity." After running a simulation to reach a desired state, extract the key values from the simulation results and manually enter them into the block dialogs. When you generate code, these initial values will be hard-coded and used for every run.
- Model Callbacks or Scripts: Automate the process of updating initial conditions by writing a MATLAB script or using model callbacks. This script runs a simulation, extracts the required state values, and programmatically updates block parameters before code generation. This ensures your generated code always starts from the latest desired state without manual intervention.
- Custom Code Integration: For advanced use cases, you can modify the generated code to accept initial state values as inputs at runtime, such as reading from a file or through an API. This approach requires in-depth knowledge of the generated code structure and is not natively supported, making it complex and suitable only for experienced users with specific deployment needs.
Refer to the following details for better understanding: https://www.mathworks.com/help/rtw/ug/how-the-generated-code-initializes-signals-states-and-parameter-data.html
Hope this helps!
Categories
Find more on General Applications in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!