Index exceeds the number of array elements (2) Error

Receiving the following error after running this code...
Index exceeds the number of array elements (2).
Error in Temp1 (line 23)
h(i) = -1 * (it(i) + vt(i)/Rleq);
deltat = .1/1000;
Tmax = 10/1000;
R = 10;
L = 20*10^-3;
V = 10;
I0 = 0;
CDA = input('Input: ');
it(1) = I0;
vt(1) = 0;
Rleq = 2*L/deltat;
Isrc = V/R;
Kmax = Tmax/deltat;
for i = 2:Kmax+1
if (i==2)&&(CDA==0)
h(i-1) = -1 * it(1);
vtemp = (Isrc + h(i-1))/(1/R + 1/Rleq);
itemp = vtemp/Rleq - h(i-1);
h(i) = -1 * itemp;
vt(i) = (Isrc + h(i))/(1/R + 1/Rleq);
it(i) = vt(i)/Rleq - h(i);
else
h(i) = -1 * (it(i) + vt(i)/Rleq);
vt(i) = (Isrc + h(i))/(1/R + 1/Rleq);
it(i) = vt(i)/Rleq - h(i);
end
end
Any help getting this code to work would be greatly appreciated!

1 commentaire

Well, it and vt are variables with one element, then your for-loop starts at 2, and tries to access the second element (looking at line 22, it(i) will be it(2) on the first iteration). That's why the "Index exceeds the number of array elements"

Connectez-vous pour commenter.

Réponses (2)

Joshua - the line of code
h(i) = -1 * (it(i) + vt(i)/Rleq);
is trying to access the third (for case i is 3) the third element of it and vt...but these have not yet been set. I suspect that you may want to do
h(i) = -1 * (it(i-1) + vt(i-1)/Rleq);
and then on the next two lines we update these two arrays as
vt(i) = (Isrc + h(i))/(1/R + 1/Rleq);
it(i) = vt(i)/Rleq - h(i);
Note that this works fine so long as the input parameter is 0 because of
if (i==2)&&(CDA==0)
If CDA is not zero then the above will never evaluate to true and you will have the same indexing problem as before.
Walter Roberson
Walter Roberson le 13 Mar 2019

0 votes

Your assignment to h(i) after the if expects vt(i) to have been assigned to. However, if the if condition was false, then the assignment statements will have been skipped, leaving vt(i) undefined.
Unfortunately you cannot just exchange the assignments to h(i) and vt(i) because vt(i) needs h(i) to have been defined
Perhaps you should be referring to vt(i-1)

Catégories

Produits

Version

R2018b

Commenté :

le 13 Mar 2019

Community Treasure Hunt

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

Start Hunting!

Translated by