for文中で30行1​列の関数から指定した​要素を抜き出そうとす​ると「インデックスが​配列要素数(1)を超​えています」というエ​ラーが出ます。

5 views (last 30 days)
和馬 廣田
和馬 廣田 on 9 Dec 2021
Commented: 和馬 廣田 on 16 Dec 2021
H = [1:1:10]';
count_number = 1;
for loop = 0:10
H = H(count_number)
 count_number = count_number + 1;
のようなプログラムを組んでいますが,エラーコードに「インデックスが配列要素数 (1) を超えています。」と表示されます。
for文内でH = H(count_number) のようにある特定の値を繰り返し次々と取り出すにはどうしたら良いでしょうか

Accepted Answer

Atsushi Ueno
Atsushi Ueno on 9 Dec 2021
Edited: Atsushi Ueno on 9 Dec 2021
> for文内でH = H(count_number) のようにある特定の値を繰り返し次々と取り出すにはどうしたら良いでしょうか
Hの要素にアクセスした結果H(count_number)をHに代入すると、Hがスカラ値として上書きされてしまうので、他の変数に結果を代入すればやりたい事が実現します。ここではHの代わりにGに代入しました。
またfor loop=0:10だと11回実行され、11回目にH(11)にアクセスする為エラーが発生します。
H = [1:1:10]';
count_number = 1;
for loop = 0:10
G = H(count_number) % ← 他の変数に結果を代入します
count_number = count_number + 1;
end
G = 1
G = 2
G = 3
G = 4
G = 5
G = 6
G = 7
G = 8
G = 9
G = 10
Index exceeds the number of array elements. Index must not exceed 10.
  1 Comment
和馬 廣田
和馬 廣田 on 16 Dec 2021
回答を読んでなぜエラーが出ていたのか納得することができました。プログラムも無事、エラーが出ずに動くようになりました。この度は回答していただき、ありがとうございました。

Sign in to comment.

More Answers (0)

Categories

Find more on Matrix Indexing in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!