How to avoid redefining optimoptions in Simulink for real-time nonlinear optimization with fmincon (SQP)?
3 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
Matt J
2025 年 7 月 25 日
編集済み: Matt J
2025 年 7 月 25 日
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
回答 (2 件)
Paul
2025 年 7 月 26 日
編集済み: Paul
2025 年 7 月 26 日
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 件のコメント
Matt J
2025 年 7 月 25 日
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 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!