The Student Room Group

MATLAB for computing the approximation of an integral.

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? :redface:
(edited 9 years ago)
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? :redface:


Yeah, it would help if you defined what all your variables were and what the hell is happening here.
Reply 2
Original post by pleasedtobeatyou
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.





(edited 9 years ago)

Quick Reply

Latest