"if" function ignoring condition

조회 수: 7 (최근 30일)
Alexandru Bortea
Alexandru Bortea 2017년 4월 17일
댓글: Andrew Newell 2017년 4월 17일
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