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)
Show older comments
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.
0 Comments
Answers (1)
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
Image Analyst
on 3 Jun 2015
I didn't really go into your algorithm. I suggest you step through it a line at a time in the debugger. See http://blogs.mathworks.com/videos/2012/07/03/debugging-in-matlab/ and you will discover what's wrong.
See Also
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!