How to use if command?

조회 수: 1 (최근 30일)
Iris Li
Iris Li 2018년 5월 21일
댓글: Iris Li 2018년 5월 21일
Say I have a table X = (columnA, columnB, columnC) What is wrong with the following command? The result is always columnB = columnA no matter what condition and which line. There are numbers in columnA smaller than 30 or larger than 90 just so you know. Thank you in advance!!
for i = 1:numel(columnA)
if 30 < columnA(i) < 90
columnB(i) = columnA(i);
else
columnB(i) = columnC(i);
end
end
end
  댓글 수: 1
Stephen23
Stephen23 2018년 5월 21일
The syntax you use does not do what you think it does. You will need to use
A<X && X<B
The syntax that you used is equivalent to this:
(A<X)<B
You can learn why by reading the MATLAB documentation:

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2018년 5월 21일
30 < columnA(i) < 90 means the same as ((30 < columnA(i)) < 90) . The first part results in 0 (false) or 1 (true), and that 0 or 1 is then compared to 90 and since both are < 90, the result of the test is always true.
MATLAB does not have any range tests of the form A < x < B , with the exception that such ranges are sometimes recognized in some MATLAB versions but only in calls to piecewise()
  댓글 수: 2
Walter Roberson
Walter Roberson 2018년 5월 21일
mask = 30 < X.ColumnA & X.ColumnA < 90;
X.ColumnB(mask) = X.ColumnA(mask);
X.ColumnB(~mask) = X.ColumnC(~mask);
Iris Li
Iris Li 2018년 5월 21일
This is easier than a loop. Thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by