How to avoid redefining optimoptions in Simulink for real-time nonlinear optimization with fmincon (SQP)?
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hello guys, I'm trying to implement a real-time nonlinear optimization solver using fmincon with the SQP algorithm in Simulink. I'm currently using a Function (Fcn) block and wrote the below optimization code inside it:
function y = fcn(u)
options = optimoptions('fmincon','Display','None','Algorithm','sqp');
x0=0.1;
lb=-10;
ub=10;
Cost_Function = @(x) f1(x,u);
y = fmincon(Cost_Function,x0,[],[],[],[],lb,ub,[],options);
end
function cost = f1(x,u)
cost=abs(x^2-u^2);
end
The code works correctly, but it's too time-consuming for my application, as the optimization needs to be performed frequently. One of the performance bottlenecks seems to be the repeated definition of "optimoptions" inside the block.
To address this, I tried defining the "options" object just once using "persistent" and "global" variables. However, Simulink throws an error, likely because options is not recognized as a Simulink parameter.
I also experimented with a "MATLAB System block" instead of the Fcn block, but the same issue persists — I can't define "optimoptions" only once at the start.
Question:
Is there a way to define optimoptions once (e.g., during initialization) and reuse it in Simulink for real-time execution, without redefining it at every simulation step?
Any suggestions or best practices for improving the performance of fmincon-based optimization in Simulink would be appreciated.
1 Kommentar
Matt J
am 25 Jul. 2025
Bearbeitet: Matt J
am 25 Jul. 2025
Is your optimization problem just a fake placeholder example? I don't see why you would be using fmincon for such a thing.The solution is obviously x=±u.
In any case, for a 1D problem, you should just use fminbnd which won't require optimoptions, if all you're trying to do is to suppress termination messages.
u=6;
lb=-10;
ub=10;
y = fminbnd(@(x) f1(x,u),lb,ub)
function cost = f1(x,u)
cost=abs(x^2-u^2);
end
Antworten (2)
Paul
am 26 Jul. 2025
Bearbeitet: Paul
am 26 Jul. 2025
If so have you tried:
function y = fcn(u)
persistent options
if isempty(options)
options = optimoptions('fmincon','Display','None','Algorithm','sqp');
end
x0=0.1;
lb=-10;
ub=10;
Cost_Function = @(x) f1(x,u);
y = fmincon(Cost_Function,x0,[],[],[],[],lb,ub,[],options);
end
function cost = f1(x,u)
cost=abs(x^2-u^2);
end
If that code in the Matlab Function block throws an error, please show the full text of the error message.
If not, please provide a link to the specific block called "Matlab (fcn)"
0 Kommentare
Matt J
am 25 Jul. 2025
You can use global variables (but with care).
function y = fcn(u)
global lb ub options
y = fminbnd(@(x) f1(x,u),lb,ub,options)
end
function cost = f1(x,u)
cost=abs(x^2-u^2);
end
0 Kommentare
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!