Why is this simple loop not working?
3 次查看(过去 30 天)
显示 更早的评论
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.
Can someone help please?
0 个评论
采纳的回答
Stephen23
2024-6-17
编辑:Stephen23
2024-6-17
"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;
5 个评论
Torsten
2024-6-17
编辑:Torsten
2024-6-17
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.
更多回答(1 个)
Avni Agrawal
2024-6-17
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!
0 个评论
另请参阅
类别
在 Help Center 和 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!