If statement in a for loop
조회 수: 2 (최근 30일)
이전 댓글 표시
I have this statement where EDist(:) is a 1x100 double which is solved for earlier in the code.
NewDist(:) = Distance(:) - EDist(:);
if NewDist(:) < 1
NewDist(:) = 20;
else
NewDist(:) = NewDist(:);
end
Inside this for loop
DS = [1:100];
for Distance = DS(:)
I'm getting NewDist as a 1x100 which is what I'm expecting... However the first 18 values of New Dist are remaining negative instead of becoming 20 when they are negative.
Why are the values of NewDist not changing despite meeting the if/else requirements of being negative?
How can I solve this problem?
댓글 수: 1
dpb
2021년 7월 23일
The short answer is in "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."
채택된 답변
Jan
2021년 7월 23일
편집: Jan
2021년 7월 23일
The if Commadn needs a scalar condition. Because NewDist(:) < 1 is a vector, Matlab inserts an all() automatically. So your code is equivalent to:
if all(NewDist(:) < 1)
...
This is not, what you want, most likely.
The line:
NewDist(:) = NewDist(:);
is a waste of time only. Just omit it.
Better with logical indexing:
tooSmall = (NewDist < 1);
NewDist(tooSmall) = 20;
In the line
DS = [1:100];
the square brackets are not useful by a (tiny) wate of time only. [ ] is the Matlab operator for a concatenation. 1:100 is a vector already and you concatenate it with nothing.
for Distance = DS(:)
This is a problem also. The for loop processes the values of its argument in columns. So this loop run 1 time only and sets Distanc to DS(:). If this is wanted, use the more direct an clear:
Distance = DS(:)
without a pseudo for loop,
추가 답변 (1개)
dpb
2021년 7월 23일
See above comment -- your IF expression is not ever TRUE unless each and every member of NewDist < 1 so it is never executed.
But, in MATLAB, you don't need the loop at all --
NewDist=Distance(:)-EDist(:);
NewDist(NewDist<1)=20;
Also NB: your use of colon operator in the above code would have the effect of setting all elements of the LHS to 20; not just those wanted. See https://www.mathworks.com/help/matlab/math/array-indexing.html
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!