x Turn on thread page Beta
 You are Here: Home >< Maths

# MATLAB for computing the approximation of an integral. watch

1. I have the following code, which works for a given function:
function s = int(f,a,b,n) % function, input: f = function, a,b
% end points, n = number of rectangles.
% output is s = approx to integral.
format long

h = (b-a)/n; % the width of each rectangle

s = 0; % running total of area of rectangles
for j=1:n % loop over all rectangles
t = t+h*f(a+(j-0.5)*h); % add the areas of each rectangle
end

disp t % display result

end

However I was experimenting about how to to use arrays in this, so far I've ended up with:

function s = intarray(f,a,b,n) % function, input: f = function, a,b are endpoints
% n = number of rectangles.
% output is s = approx to integral.

t = zeros(1,n);

a = t(1);

b = t(n);

h = (b-a)/n;
for j=2:n-1
t(j) = a + j*h;
s = h/2*(f(a) + f(b)) + h*(t(j)+t(j-1));
end
disp s
end

The main problem seems to be the for loop. I can't have it go from 1:n-1, it will result in an error.

Any help?
2. (Original post by TheBBQ)
I have the following code, which works for a given function:

function t = int(f,a,b,n)
format long
h = (b-a)/n;
t = 0.5*h*(f(a)+f(b));
for j=1:n-1
t = t + h*f(a+j*h);
end
disp t
end

However I was experimenting about how to to use arrays in this, so far I've ended up with:

function s = intarray(f,a,b,n)
t = zeros(1,n);
a = t(1);
b = t(n);
h = (b-a)/n;
for j=2:n-1
t(j) = a + j*h;
s = h/2*(f(a) + f(b)) + h*(t(j)+t(j-1));
end
disp s
end

The main problem seems to be the for loop. I can't have it go from 1:n-1, it will result in an error.

Any help?
Yeah, it would help if you defined what all your variables were and what the hell is happening here.
Yeah, it would help if you defined what all your variables were and what the hell is happening here.
Oops, sorry, this should explain everything:

s or t are the integrals of a function f(t) with end points a to b.
n = number of "rectangles"

I'm using the following method to approximate the integral numerically.

TSR Support Team

We have a brilliant team of more than 60 Support Team members looking after discussions on The Student Room, helping to make it a fun, safe and useful place to hang out.

This forum is supported by:
Updated: January 10, 2015
Today on TSR

### How much will your degree earn you?

Find out where yours ranks...

Poll
Useful resources

### Maths Forum posting guidelines

Not sure where to post? Read the updated guidelines here

### How to use LaTex

Writing equations the easy way

### Study habits of A* students

Top tips from students who have already aced their exams