If statement in a for loop
Show older comments
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
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."
Accepted Answer
More Answers (1)
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
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!