In: Computer Science
Give me a MATLAB code which integrates any function using Romberg integration
The code must work fine or else I will down vote the answer badly
Dont post if you dont know
The given MATLAB CODE takes any function and integrates it as per the rule of Romberg as per various levels and prints the result. The intermediate trapezoidal rule code is also shown
The sample is shown for f(x)=1/(1+x) for 5 levels from 0 to 1
clc;clear all
format long
f=@(x) 1./(1+x);
a=0;b=1;h=1;n=5;
ans1=RombergIntegration(f,a,b,h,5);
fprintf('Desired answer is %5.6f \n',ans1(1,n+1))
function I=RombergIntegration(f,a,b,s,level)
for(j=1:(level+1))
ni=s*2^(j-1);
I(j,1)=trapezoidal(f,a,b,ni);
end
for(j=2:level+1)
for(k=1:(level-j+2))
I(k,j)=(4^(j-1)*I(k+1,j-1)-I(k,j-1))/(4^(j-1)-1);
end
end
end
function answer=trapezoidal(f,a,b,n)
i(1)=f(a); i(n+1)=f(b);
h=(b-a)/n;
x=a:h:b;
i(2:n)=2*f(x(2:(length(x)-1)));
answer=0.5*h*sum(i);
end