Index exceeds the number of array elements (2) Error

조회 수: 78 (최근 30일)
Joshua Steil
Joshua Steil 2019년 3월 13일
댓글: Brian Hart 2019년 3월 13일
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
Brian Hart
Brian Hart 2019년 3월 13일
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"

댓글을 달려면 로그인하십시오.

답변 (2개)

Geoff Hayes
Geoff Hayes 2019년 3월 13일
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 2019년 3월 13일
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)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by