MATLAB Answers

If statement in a for loop

조회 수: 3(최근 30일)
Noah Reilly
Noah Reilly 2021년 7월 23일
댓글: Noah Reilly 2021년 7월 24일
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
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
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
Noah Reilly
Noah Reilly 2021년 7월 24일
Thanks fo the concern on the for loop and column vector, but I end up just transposing it later in the loop so it doesn't affect anything. But good Solution!

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

추가 답변(1개)

dpb
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

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by