"if" function ignoring condition
7 次查看(过去 30 天)
显示 更早的评论
I am trying to condition the RPM of an engine for a Launch control system. However with my function, the time t is completely ignored, the if loop going straight to the else part instead of holding constant RPM until t is bigger than I want. I also attached the variables so you can run the code yourself.
function rpm = rpm_fun(omega,gr,t)
global LCREV_MAX
if t < 1.5; % time during simulation, when clutch is engaged
rpm = LCREV_MAX;
else
rpm = omega.*60.*gr/(2*pi);
end
0 个评论
采纳的回答
Steven Lord
2017-4-17
Is t a vector? If so, take a look at the first paragraph of the Description section of the documentation for the if keyword.
"if expression, statements, end evaluates an expression, and executes a group of statements when the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false."
If t is a vector, as I suspect, the body of the if will only be executed if ALL the elements of t are less than 1.5. If even one element of t is not less than 1.5, the body of the else will execute.
If you want your function to return a vector of values the same size as t whose values contain one of the two values LCREV_MAX or omega.*60.*gr/(2*pi), use logical indexing.
2 个评论
Andrew Newell
2017-4-17
Alexandru, you need to use the indexing on both sides. Here is a fix:
idx = t>LCREV_MAX;
rpm(idx) = omega(idx).*60.*gr(idx)./(2*pi)
更多回答(0 个)
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!