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 Center および File ExchangeProgramming についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by