If statement in a for loop

1 view (last 30 days)
Noah Reilly
Noah Reilly on 23 Jul 2021
Commented: Noah Reilly on 24 Jul 2021
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 Comment
dpb
dpb on 23 Jul 2021
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."

Sign in to comment.

Accepted Answer

Jan
Jan on 23 Jul 2021
Edited: Jan on 23 Jul 2021
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 Comment
Noah Reilly
Noah Reilly on 24 Jul 2021
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!

Sign in to comment.

More Answers (1)

dpb
dpb on 23 Jul 2021
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

Categories

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

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!