Index exceeds the number of array elements (10).

1 次查看(过去 30 天)
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 个评论
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 CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by