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

3 views (last 30 days)
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)

Accepted Answer

Voss
Voss on 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 Comments
Andrew Mosqueda
Andrew Mosqueda on 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 on 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);

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!