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

 Akzeptierte Antwort

Mohammed Shaheen
Mohammed Shaheen am 21 Sep. 2026 um 12:03
Bearbeitet: Mohammed Shaheen am 21 Sep. 2026 um 12:04
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.

1 Kommentar

@Mohammed Shaheen. Thanks a lot for your answers, the simulation results are correct after saving the onlinedata.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Produkte

Version

R2026a

Gefragt:

am 8 Sep. 2026 um 8:08

Kommentiert:

am 21 Sep. 2026 um 12:48

Community Treasure Hunt

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

Start Hunting!

Translated by