function handle in a loop
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Sarah Kern
el 22 de En. de 2020
Comentada: Walter Roberson
el 23 de En. de 2020
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 comentarios
Respuesta aceptada
Walter Roberson
el 22 de En. de 2020
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 comentarios
Walter Roberson
el 23 de En. de 2020
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
Más respuestas (1)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!