I am trying to create a while loop where a marker can't leave a box of x = -10 and y = 10, y = -10. Once the marker reaches x = 11 I want the loop to stop.

1 view (last 30 days)

Accepted Answer

Torsten
Torsten on 9 Mar 2024
Moved: Torsten on 9 Mar 2024
Put the k = k+1 at the end of the while-loop, not at the beginning.
And if x(k) == -10, you only set x(k+1), but not y(k+1). This will lead to an access error for y(k+1) after k is increased by 1 for the next step.
  1 Comment
Voss
Voss on 9 Mar 2024
To avoid that error: whatever value k has, x has to have at least k elements. That means, since you are incrementing k to k+1 on each iteration of the loop, you need to assign x(k+1) on each iteration of the loop.
But in this case x(k+1) is not assigned:
else if x(k) == -15 & y(k) == -15
y(k+1) = y(k) + 1;
y(k+1) = y(k) + 1;
k = k+1
Maybe it should be this instead?
else if x(k) == -15 & y(k) == -15
x(k+1) = x(k) + 1;
y(k+1) = y(k) + 1;
k = k+1

Sign in to comment.

More Answers (0)

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!