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