function handle in a loop
조회 수: 3 (최근 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!