function handle in a loop
5 次查看(过去 30 天)
显示 更早的评论
Hello,
I have the following objective function in my optimization matlab function block
if f_lag > 0 % decision braking or driving mode
fun =@(x) (A/SOC_1)*(b(1))^2+(A/SOC_2)*(x(2))^2+(A/SOC_3)*(x(3))^2+(A/SOC_4)*(x(4))^2+d_delay_1-(SW_1+x(5))+d_delay_2-(SW_2+x(6))+d_delay_3-(SW_3+x(7))+d_delay_4-(SW_4+x(8));
else
fun =@(x) ((B*M_reg_1)/SOC_1)*(1/(x(1))^2)+((B*M_reg_2)/SOC_2)*(1/(x(2))^2)+((B*M_reg_3)/SOC_3)*(1/(x(3))^2)+((B*M_reg_4)/SOC_4)*(1/(x(4))^2)+d_delay_1-(SW_1+x(5))+d_delay_2-(SW_2+x(6))+d_delay_3-(SW_3+x(7))+d_delay_4-(SW_4+x(8));
end
but because of code generation simulink/matlab, doesnt allow the function handles in the if loop.
Can someone help me what to do?
would be very glad, thank you!
0 个评论
采纳的回答
Walter Roberson
2020-1-22
Provided that the two calculations return the same size of values, and provided that neither calculation ever returns inf or nan, then the general form
if condition
f = @(x) expression1
else
f = @(x) expression2
end
Can be rewritten as
f = @(x) (condition).*expression1 +
(~condition).*expression2
This is seldom the most efficient approach. Typically it would be more efficient to create both function handles and later test which one should be used.
2 个评论
Walter Roberson
2020-1-23
That code looks plausible.
It will let you create both function handles: just store them in different variables and invoke the appropriate one. You might even be able to store them in a cell array and index that at (f_lag+3)/2
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!