Index exceeds the number of array elements. Index must not exceed 1.

조회 수: 4 (최근 30일)
Andrew Mosqueda
Andrew Mosqueda 2022년 9월 19일
댓글: Voss 2022년 9월 22일
Pretty novice at MATLab, I'm having trouble creating a loop for my coastal engineering class. It'll run the first itieration but nothing after.
P1=load("HW2_Problem1_PeriodandH.txt");
T=P1(1:3:7,1);
H=P1(1:3,2);
for i=1:3
T=T(i)
Ko=1/(9.8*T.^2/(2*pi)^2)
end
Index exceeds the number of array elements. Index must not exceed 1.
Error in HW2 (line 11)
T=T(i)

채택된 답변

Voss
Voss 2022년 9월 19일
This line:
T=T(i)
takes the ith element of T and stores it as T, after which T is a variable with one element. So any subsequent attempt to access T(i) when i > 1 will fail because T has only one element.
Instead, use another variable (i.e., don't overwrite T):
for i=1:3
Ti=T(i)
Ko=1/(9.8*Ti.^2/(2*pi)^2)
end
Or better, just use T(i) when you need it (no need for another variable at all):
for i=1:3
Ko=1/(9.8*T(i).^2/(2*pi)^2)
end
  댓글 수: 2
Andrew Mosqueda
Andrew Mosqueda 2022년 9월 19일
Thank you. I used the latter code and it runs, however, I'd like to save my Ko answers in a matrix for later use and it only saves the 3rd itieration. How would I go about this?
Voss
Voss 2022년 9월 22일
Make Ko a vector and calculate one element of it on each iteration of the loop:
for i=1:3
Ko(i)=1/(9.8*T(i).^2/(2*pi)^2)
end
Of course, if that's all it does, the for loop is not needed at all:
Ko = 1./(9.8*T.^2/(2*pi)^2);

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

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by