If statement in a for loop
显示 更早的评论
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."
采纳的回答
更多回答(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
类别
在 帮助中心 和 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!