Index exceeds the number of array elements (10).

1 回表示 (過去 30 日間)
Nick mardero
Nick mardero 2020 年 10 月 21 日
コメント済み: Star Strider 2020 年 10 月 21 日
Having troubble with the last loop (it runs fine without it) i know its not the most elegent code but im pretty new to this. please explain like im 4 years old*
clear;
x=[1 2 3.25 4.5 6 7 8 9 9.5 10];
y=[5 6 5.5 7 8.5 8 6 7 7 5];
plot(x,y);
n=length(x);
for i=1:n-1
line([x(i) x(i)],[0 y(i)]);
end
A=zeros(1,n-1);
Area=0;
for i=1:2 & 4:5
A(i)=0.5*(x(i+1)-x(i))*(y(i+1)+y(i));
Area=Area+A(i);
end
for i=2:4 & 8:10
A(i)=(x(i+2)-x(i))*((y(i)+4*y(i+1)+y(i+2))/6);
Area=Area+A(i);
end
for i=5:8
A(i)=(x(i+3)-x(i))*((y(i)+3*y(i+1)+3*y(i+2)+y(i+3))/8);
Area=Area+A(i);
end

回答 (1 件)

Star Strider
Star Strider 2020 年 10 月 21 日
In this line:
A(i)=(x(i+3)-x(i))*((y(i)+3*y(i+1)+3*y(i+2)+y(i+3))/8);
↑ ← HERE
when ‘i’ is 8, addresses ‘y(11)’ when ‘y’ has only 10 elements.
  2 件のコメント
Nick mardero
Nick mardero 2020 年 10 月 21 日
so how would i fix this?
Star Strider
Star Strider 2020 年 10 月 21 日
The easiest way:
for i=5:7 STOP AT 7
A(i)=(x(i+3)-x(i))*((y(i)+3*y(i+1)+3*y(i+2)+y(i+3))/8);
Area=Area+A(i);
end
Of course an even easier way would be:
A = cumtrapz(x,y)
although you’re likely not allowed to do that.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by