Why is this simple loop not working?
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Scott Banks
le 17 Juin 2024
Commenté : Scott Banks
le 17 Juin 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.
Can someone help please?
0 commentaires
Réponse acceptée
Stephen23
le 17 Juin 2024
Modifié(e) : Stephen23
le 17 Juin 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;
5 commentaires
Torsten
le 17 Juin 2024
Modifié(e) : Torsten
le 17 Juin 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.
Plus de réponses (1)
Avni Agrawal
le 17 Juin 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!
0 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!