Hi I have made a function in matlab to calculate the Integral of a function usin
ID: 3587913 • Letter: H
Question
Hi I have made a function in matlab to calculate the Integral of a function using the trapizium rule and it works perfectely but now I'm wanted to calculate the the integral using the left hand rule and then the right. It's meant to be a simple adaptation but I can't figure it out from my notes. I've posted the code below and you dont need to change unless you want too but could you tell me what I need to change and what to, to make it the left and right hand rule instead. Thanks.
CODE:
------------------------------------------------------------------
function [ I ] = trapRule( f, a, b, dx )
%Calculating Numerical of function using trap rule
% Given (function, xmin, xmax and dx)
%Creating xArray from given values
xArray = a : dx : b ;
%Creating yArray from function and xArray
yArray = f(xArray) ;
%summing interior of yArray
%values for sum
N = length(yArray) - 2 ;
ySum = 0 ;
%summing
for ii = 1:N
ySum = ySum + yArray(1,ii+1);
end
%trap rule
I = dx.*(0.5.*(f(a)+f(b))+ySum);
end
------------------------------------------------------------------------
Explanation / Answer
function [ I ] = lefthandRule( f, a, b, dx )
%Calculating Numerical of function using left hand rule
% Given (function, xmin, xmax and dx)
%Creating xArray from given values
xArray = a : dx : b ;
%Creating yArray from function and xArray
yArray = f(xArray) ;
width=dx;
%Left hand rule integrats by dividing the function into rectangles of width
%equal to dx and height equal to function value for the x on left side of
%rectangle
%here width = dx.
%for height:if rectangle is formed between x1 and x2,then height will be
%f(x1) since it is on the left side
I=0;
for i=1:length(yArray-1)
I=I+width*yArray(i);
end
==========================================================
function [ I ] = righthandRule( f, a, b, dx )
%Calculating Numerical of function using right rule
% Given (function, xmin, xmax and dx)
%Creating xArray from given values
xArray = a : dx : b ;
%Creating yArray from function and xArray
yArray = f(xArray) ;
width=dx;
%Right hand rule integrates by dividing the function into rectangles of width
%equal to dx and height equal to function value for the x on right side of
%rectangle
%here width = dx.
%for height:if rectangle is formed between x1 and x2,then height will be
%f(x2) since it is on the right side
I=0;
for i=2:length(yArray)
I=I+width*yArray(i);
end