Control Underactuated Two-Link Robot Using C/GMRES Solver Example Generates Distinct Result

I was learning Nonlinear Model Predictive Controller (NMPC) recently and tried to reproduce the Control Underactuated Two-Link Robot Using C/GMRES Solver Example in the MATLAB Online platform. When I run the all code sections first time, the simulation result is correct. However, when I run the Closed Loop Simulation (CLS) code section repeatedly, the simulation result is different.
Through debugging, I find that the problem was caused by Code Generation section. For obtaining correct result, I have to run the code generation to reproduce the .mex function.
I would like to know why it is necessary to generate mex file every time in order to obtain correct simulation result.
Fig 1. correct result with reprodecing mex file Fig 2. result without reproducing mex file

 Accepted Answer

Hi,
The behaviour is observed because of the variable "onlinedata" in the example:
  • The controller keeps its previous calculations in onlinedata.
  • Rerunning only the simulation resets the robot, but not this controller memory.
  • The controller then uses old calculations with a newly reset robot, so the output changes.
So if you want to run the Closed Loop Simulation(CLS) section multiple times without changing the output. Do the following:
Save a clean copy of onlinedata after setup in the Code Generation section
onlineDataClean = onlinedata;
Before each new simulation, reset onlinedata to that copy
% Initialize data storage
N = FinalTime/Ts;
tHistory = 0:Ts:FinalTime;
xHistory = zeros(N+1,4);
uHistory = zeros(N+1,1);
onlinedata = onlineDataClean; %Add this line in the CLS section
No MEX regeneration is needed here. and you can run the Closed Loop SImulation section multiple times and get the correct simulation result
I hope this helps.
Thanks.

More Answers (0)

Categories

Find more on Model Predictive Control Toolbox in Help Center and File Exchange

Products

Release

R2026a

Asked:

on 8 Sep 2026 at 8:08

Commented:

about 13 hours ago

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!