Amber
Amber

Reputation: 43

Using Trapezium Rule on any function and show a graph

I have successfully managed to create a code in which I can estimate the area beneath the curve using the Trapezium rule. What I am struggling to do is plot the corresponding graph. I've used x^2 as the example and in the image I've attached a=-5, b=5 and n=3. And the original x^2 graph is not coming up but rather a merge between the blue and green lines. Can someone help fix this? Thank you.

Figure 1

% Trapezium Rule
f=@H; % Input Function
 a=input('Enter lower limit a: '); 
 b=input('Enter upper limit b: ');  
 n=input('Enter the no. of interval: ');  
 h=(b-a)/n;
 sum=0;
 % Sum of f(x_1) to f(x_n+1)
 for k=1:1:n+1
  x(k)=a+k*h;
  y(k)=f(x(k));
  sum=sum+y(k);
 end
hold on
plot(x, y,'bo-');
% drawing of the function
plot([x(1:end); x(1:end)], [zeros(1,length(y)); y(1:end)], 'r-');
% vertical lines from the points
plot([x(1:end-1); x(2:end)], [y(1:end-1) ; y(1: end)], 'g--');
% Meant to be forming a trapizium
hold off
answer = (h*0.5)*(sum);
% answer=h/2*(f(a)+f(b)+2*sum);
fprintf('\n The value of integration is %f',answer);

function y = H(x)
    y = x.^2;
end 

Upvotes: 1

Views: 154

Answers (1)

Ander Biguri
Ander Biguri

Reputation: 35525

Your green line does not go from the same value to the same value! It foes from one to the next. You forgot that.

% the only reason you do -1 is so the last y can go to the end! The same as x
plot([x(1:end-1); x(2:end)], [y(1:end-1) ; y(2: end)], 'g--');

Upvotes: 1

Related Questions