Clear Filters
Clear Filters

"if" function ignoring condition

4 views (last 30 days)
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

Accepted Answer

Steven Lord
Steven Lord on 17 Apr 2017
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 Comments
Alexandru Bortea
Alexandru Bortea on 17 Apr 2017
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 on 17 Apr 2017
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)

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!