MATLAB Answers

0

Using a while loop with a vector

Asked by Tim Stark on 2 May 2019
Latest activity Commented on by Tim Stark on 3 May 2019
Hey guys I'm running in to a problem with a 'while loop'. A simplified version of my codes look likes this:
B = [361;362;363;1000;10000;100000];
while B > 360
B = B - 360;
end
which yields:
B =
1
2
3
640
9640
99640
What I dont understand is this: why does my while loop not repeat until the last three elements of my matrix are < 360.
Thanks in advance

  0 Comments

Sign in to comment.

Tags

Products


Release

R2019a

1 Answer

Answer by Kevin Phung on 2 May 2019
 Accepted Answer

Your while loop actually only runs once because after the first iteration, B>360 returns a logical array of [0 0 0 1 1 1], so it does not loop a second time. I think you meant to do something like this:
B = [361;362;363;1000;10000;100000];
for i = 1:numel(B)
while B(i) > 360
B(i) = B(i) - 360;
end
end
which will return:
1
2
3
280
280
280

  1 Comment

Thanks!

Sign in to comment.