# Why is this simple loop not working?

3 views (last 30 days)
Scott Banks on 17 Jun 2024
Commented: Scott Banks on 17 Jun 2024
Hi there,
I think I have used this procedure for the following loop many times, but now it isn't working:
h = 3
z = 4
y = 0
x = 0
for i = 1:3
z(i+1) = z(i) + (2*y(i) + 8*x(i)*(9 - x(i)))*h
y(i+1) = y(i) + z(i)*h
z(i) = z(i+1);
y(i) = y(i+1);
x(i) = x(i) + h
end
I keep getting an error saying Index must not exceed 1.
I don't know why this is happening.

Stephen23 on 17 Jun 2024
Edited: Stephen23 on 17 Jun 2024
"I don't know why this is happening."
The problem is very simple: you do not extend x in the same way that you extend y and z.
For both y and z you extend them using the indexing i+1 before trying to access that new index position. No problems with them!
However, with x you try and access x(i) on the next loop iteration without making any attempt to define that index position first. In other words, you never make x larger. So on the 2nd loop iteration, your code tries to access x(2) which does not exist!
"I think I have used this procedure for the following loop many times, but now it isn't working:"
Nope, it never worked trying to access an index position that does not exist. You must have changed something.
Perhaps the last line should be this?:
x(i+1) = x(i) + h;
Torsten on 17 Jun 2024
Edited: Torsten on 17 Jun 2024
When the loop index goes from i to i+1, you will automatically plug in z(i+1) for z(i). Your setting z(i) = z(i+1) only deletes z(i) and replaces it by z(i+1) which usually is unwanted.
I suggest you test what you get for the variables with your loop and make a parallel calculation with pencil and paper.
Scott Banks on 17 Jun 2024
yes, sorry, you are right. I think I did that because sometimes in this situation I might assign y0, y1, z0 z1 etc rather than indexing them with 'i'. Anyways, it's good to know going foward. Thanks.

Avni Agrawal on 17 Jun 2024
I understand that the error message you are encountering is "Index must not exceed 1,". This suggests that MATLAB is treating `z`, `y`, and `x` as scalar variables, not arrays. This happens because you initialized `z`, `y`, and `x` as scalars (single values) rather than as vectors or arrays. When you attempt to access or assign a value to an index greater than 1 (e.g., `z(i+1)`), MATLAB throws an error because it expects `z` to have only one element.
To fix this issue, you need to initialize `z`, `y`, and `x` as arrays with predefined sizes before the loop. Additionally, ensure `h` is defined before the loop. If `h` is not defined, MATLAB will throw an error because it won't know how to increment `x` or calculate the new values for `y` and `z`.
I hope this helps!