Index Exceeds Matrix Dimensions error in For Loop

1 vue (au cours des 30 derniers jours)
Jon Stapchuck
Jon Stapchuck le 11 Fév 2021
Commenté : Jon Stapchuck le 11 Fév 2021
Hello,
As the title says, I keep on getting this error and not too sure how to fix it, as I am not too familiar with MATLAB.
A shortened version of the code is as followed:
L=10;
T(1)=200;
for i=2:(L-1)
F(i)=T(i-1);
end
Ultimately, I will have three different functions, F1, F2, and F3, that call T(i-1), T(i), and/or T(i+1) as i runs from 2 to (L-1), but the T(1) will be given, which is why I begin my loop with T(i-1), so I can call the previous T(i) value for the new i, if that makes sense.
But to make things simple, I just included this smaller, simplified version since I'm assuming if I can fix this error I can figure out what to do for the longer code.
Any help is appreciated, thank you. I can give more details if need be as well.

Réponses (2)

randerss simil
randerss simil le 11 Fév 2021
%if true
L = 10;
F1 = zeros(1,L)
F2 = zeros(1,L)
F3 = zeros(1,L)
T1(1)=200;
T2 = zeros(1,L);
T3 = zeros(1,L);
T3(3)=400;%e.g.
F1(1,1) = 0;
F2(1,1) = 0;
F3(1,1) = 0;
for i=2:(L-1)
F1(i)=F1(i-1)+T1(i-1);
F2(i)=F2(i-1)+T2(i);
F3(i)=F3(i-1)+T3(i+1);
end
  1 commentaire
Jon Stapchuck
Jon Stapchuck le 11 Fév 2021
So if I understand this correctly, we have to initially define all functions and variables used (in this case F1, F2, F3) such that they can run from 1 to L.
Thank you, I see your edits and will apply them. A difference is that I want my T values (besides certain initial and final ones) to be changing with i as well, but I can do that in a for loop as well.

Connectez-vous pour commenter.


Walter Roberson
Walter Roberson le 11 Fév 2021
T(1)=200;
for i=2:(L-1)
F(i)=T(i-1);
end
You only initialize T(1) and you never assign to T(2) so when i becomes 3 you try to refer to T(2) which does not exist.
  1 commentaire
Jon Stapchuck
Jon Stapchuck le 11 Fév 2021
Yes that will do it haha, thank you very much.
Ultimately my plan is to have the T's be varying with i as well

Connectez-vous pour commenter.

Catégories

En savoir plus sur 2-D and 3-D Plots dans Help Center et File Exchange

Produits


Version

R2017a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by