for loop: Attempted to access y(2); index out of bounds because numel(y)=1. How to solve this error?

1 view (last 30 days)
a=1;
b=2;
n=10;
h=(b-a)/n;
x(1)=a;
for i=a:n
x(i+1)=x(i)+h;
y(i)=x(i).^3;
area2(i)=((((y(i)-0)+(y(i+1)-0))/2)*x(i));
end
totalarea=sum(area2);
disp(totalarea)
end
In this foor loop i am trying to find the area of the function y=x^3 in the boundaries 1 and 2 using the trapezium rule. With the for loop i get the values of x for each stepsize and then the values of y for each value of x but when i try to calculate the area for each trapezium i get this error: Attempted to access y(2); index out of bounds because numel(y)=1. The total area of the integral is then the sum of all areas but with this error i dont know how to continue. Thanks in advance.

Answers (1)

Image Analyst
Image Analyst on 3 Jun 2015
When you go to calculate area, you use y(i+1) but you have not assigned y(i+1) yet. So why not calculate the x and y first, then calculate the areas after that:
a=1;
b=2;
n=10;
h=(b-a)/n;
x(1)=a;
for i=a:n
x(i+1)=x(i)+h;
y(i)=x(i).^3;
end
for i=a:n-1
area2(i)=((((y(i)-0)+(y(i+1)-0))/2)*x(i));
end
totalarea=sum(area2);
disp(totalarea)
  2 Comments
Alvaro García
Alvaro García on 3 Jun 2015
I dont know why but this is not working, it gives a number too big when the answer should be around 3.75, i dont know where is the error.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!