Trapezoidal Rule in MATLAB

Below is the matlab code for Trapezoidal Rule :

x=[0 .2 .4 .6 .8 1]
n=6;
h=(x(6)-x(1))/5
for i=1:n
y(i)=1/(1+x(i)*x(i));
end
sum=h/2*(y(1)+y(6)+2*(y(2)+y(3)+y(4)+y(5)))


Save the file with a .m extension.
Then on  the command window run the file by typing filename.m

The output the above program will be something like this :

x =

         0    0.2000    0.4000    0.6000    0.8000    1.0000


h =

    0.2000


sum =

    0.7837

Top