Cannot convert logical to casadi.SX
조회 수: 19 (최근 30일)
이전 댓글 표시
Hello
I am currently working with a solver ForcesPro to implement MPC. The solver itself requires a software CasADi to generate derivatives to solve an NLP problem. CasADi converts the variables being used into SX variables to carry out its computation and it is apparently not allowed to use logical if on these variables.
The following is my code snippet (u is a variable of type SX):
if (u>=0)
f = (B.b1*v^2*C^2 +B.b2*v^2*C + B.b3*v^2 + B.b4*v*C^2 + B.b5*v*C + B.b6*v + B.b7*C^2 + B.b8*C +B.b9)*W;
else
f=0;
end
and it returns the following error
Conversion to logical from casadi.SX is not possible.
Error in Longitudinal_Control>f (line 187)
if (u>=0)
I thought the problem is similar to the one faced during implementing if statements for symbolic variables thus I implemented the function peicewise():
f = piecewise(u>=0, (B.b1*v^2*C^2 +B.b2*v^2*C + B.b3*v^2 + B.b4*v*C^2 + B.b5*v*C + B.b6*v + B.b7*C^2 + B.b8*C +B.b9)*W, u<0, 0);
But got the follwing error:
Undefined function 'piecewise' for input arguments of type 'casadi.SX'.
which is rather understandable.
Therefore, if anyone knows how to implement IF statements for CasADi symbolic variables in MATLAB please let me know.
I have already checked CasADi's documentation but it was not helpful.
Thanks in advance!
댓글 수: 0
답변 (2개)
Ruven Weiss
2023년 2월 28일
편집: Ruven Weiss
2023년 2월 28일
There is a special if_else function in CasADi:
if_else(condition, true-case, false-case)
For example:
import casadi.*
x = SX.sym('x');
y = if_else(x >= 0, x^2, -x^2);
here, y is evaluated to x^2 if x>=0 and to -x^2 if x<0.
Ayush
2025년 1월 21일
I understand you are trying to implement if statements for CasADi symbolic variables in MATLAB.
Here is the syntax for the same:
import casadi.*
x = SX.sym("x")
f0 = Function("f0",[x],[sin(x)])
f1 = Function("f1",[x],[cos(x)])
f2 = Function("f2",[x],[tan(x)])
f_cond = Function.conditional('f_cond', [f0, f1], f2)
print(f_cond)
Here is an example MATLAB code for your reference:
x = SX.sym('x');
f0 = Function('f0',{x},{sin(x)});
f1 = Function('f1',{x},{cos(x)});
f2 = Function('f2',{x},{tan(x)});
f_cond = Function.conditional('f_cond', {f0, f1}, f2);
disp(f_cond);
You can read more about these conditional statement here: https://web.casadi.org/docs/#conditional-evaluation
Hope it helps!
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Communications Toolbox에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!