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

3 visualizaciones (últimos 30 días)
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)

Respuesta aceptada

Voss
Voss el 19 de Sept. de 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 comentarios
Andrew Mosqueda
Andrew Mosqueda el 19 de Sept. de 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 el 22 de Sept. de 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);

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by