Index exceeds the number of array elements (2) Error

81 Ansichten (letzte 30 Tage)
Joshua Steil
Joshua Steil am 13 Mär. 2019
Kommentiert: Brian Hart am 13 Mär. 2019
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 Kommentar
Brian Hart
Brian Hart am 13 Mär. 2019
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"

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Geoff Hayes
Geoff Hayes am 13 Mär. 2019
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 am 13 Mär. 2019
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)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by