Index exceeds the number of array elements (10).

1 Ansicht (letzte 30 Tage)
Nick mardero
Nick mardero am 21 Okt. 2020
Kommentiert: Star Strider am 21 Okt. 2020
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

Antworten (1)

Star Strider
Star Strider am 21 Okt. 2020
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 Kommentare
Nick mardero
Nick mardero am 21 Okt. 2020
so how would i fix this?
Star Strider
Star Strider am 21 Okt. 2020
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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by