I've implemented the trapezoidal rule to compute the integral for a function \$x^2\$. I would like to see another style of the same code. It seems Matlab hates for a matrix to be expanded without specifying the size.
clear all
clc
n = 5; % number subdivisions
a = 1.0; % lower limit
b = 2.0; % upper limit
sum = 0.0;
dx = (b-a)/(n-1); % step size
% Generate samples
for i = 1:n
x(i) = a + (i-1)*dx;
end
% Generate function's values
for i = 1:n
y(i) = x(i).^2;
end
% Compute area using Trapz. method
for i = 1:n
if ( i == 1 || i == n) % for the first and last data
sum = sum + y(i)./2;
else
sum = sum + y(i); % for the rest of data
end
end
area = sum * dx;
area
2.3333
not what you said2.34
is using the analytical form of the function however trapezoidal method is a method to approximate the analytical function. The error here is0.45 %
which means we have some level of uncertainty in the estimated result. \$\endgroup\$Answer: 2.34375
which is same of mine. Even thoughn=5
in my code but the loop start from0
to4
. Check the implementation of my code. \$\endgroup\$