"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

采纳的回答

Steven Lord
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 个评论
Alexandru Bortea
Alexandru Bortea 2017-4-17
Thank you very much for explaining the if expression. Using what you told me I got up to here, however, now i get the error that "In an assignment A(I) = B, the number of elements in B and I must be the same.", even though the when debugging they both appear as vectors.
function rpm = rpm_fun(omega,gr,t)
global LCREV_MAX
rpm=t;
rpm (:) = LCREV_MAX;
rpm (t > 1.5) = omega.*60.*gr./(2*pi);
Andrew Newell
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 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by