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

3 Ansichten (letzte 30 Tage)
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)

Akzeptierte Antwort

Voss
Voss am 19 Sep. 2022
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 Kommentare
Andrew Mosqueda
Andrew Mosqueda am 19 Sep. 2022
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 am 22 Sep. 2022
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);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by