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

 채택된 답변

Mohammed Shaheen
Mohammed Shaheen 2026년 9월 21일 12:03
편집: Mohammed Shaheen 2026년 9월 21일 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

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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

제품

릴리스

R2026a

태그

질문:

2026년 9월 8일 8:08

댓글:

2026년 9월 21일 12:48

Community Treasure Hunt

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

Start Hunting!

Translated by