In: Advanced Math
Write a Matlab script-file probl1.m to execute the requested commands (as much as possible) in the exercises below. Increase N a number of times according to N = 4, 8, 16, 32, 64, 128, . . . (1) Determine for each N the (exact) error. (2) Determine for N ≥ 16 also the convergence ratio q(h/2).
This script should be based on a function-file trap.m (trapezoidal integration) as follows:
function [totarea] = trap(N)
format long;
a = 0; b = 1/2; h = (b-a)/N;
x = a:h:b; totarea = 0;
for i = 1:N
xl = x(i);
xr = x(i+1);
fxl = myfunct(xl);
fxr = myfunct(xr);
locarea = (h/2)*(fxl+fxr);
totarea = totarea + locarea;
end
end
You can refer to the integral as myfunct(). The interval is [0,1/2].
%Matlab code for Trapizoidal method
clear all
close all
%Matlab code for Trapizoidal integral for varing N
n=[4 8 16 32 64 128 256];
%exact integral for given myfunct(x) is 0.75;
for i=1:length(n)
N=n(i);
[totarea] = trap(N);
err(i)=abs(totarea-0.75);
fprintf('For N=%d integral using Trapizoidal is
%f with error %e\n',N,totarea,err(i))
if i>=3
fprintf('\tConvergence
ratio =%f\n',err(i)/err(i-1))
end
end
%function for integrand
function f=myfunct(x)
f=3*x^2+5*x;
end
%function for Trapizoidal integral
function [totarea] = trap(N)
format long;
a = 0; b = 1/2; h = (b-a)/N;
x = a:h:b; totarea = 0;
for i = 1:N
xl = x(i);
xr = x(i+1);
fxl = myfunct(xl);
fxr = myfunct(xr);
locarea = (h/2)*(fxl+fxr);
totarea = totarea + locarea;
end
end
%%%%%%%%%%%%%% End of code %%%%%%%%%%%%%%%