# function handle in a loop

18 views (last 30 days)
Sarah Kern on 22 Jan 2020 at 17:38
Commented: Walter Roberson on 23 Jan 2020 at 8:58
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!

Walter Roberson on 22 Jan 2020 at 20:57
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.

Sarah Kern on 23 Jan 2020 at 8:33
Thank you very much, so like this?
f =@(x) (f_lag == 1).*(A/SOC_1)*(x(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));
+ (f_lag == -1).*((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));
It wont let me create both function handles, that's what I tried before.
Walter Roberson on 23 Jan 2020 at 8:58
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

Sarah Kern on 23 Jan 2020 at 8:32
Thank you very much, so like this?
f =@(x) (f_lag == 1).*(A/SOC_1)*(x(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));
+ (f_lag == -1).*((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));
It wont let me create both function handles, that's what I tried before.