clear all % clear all variables close all % closes figures between each run clc % clear command window between each run format short % to see only 5 digits % format long % uncomment to see manny digits x = 0:pi/4:pi; % [rad] 1x5 vector % Type size(x) in Command window or check size of vecs in Workspace window y = sin(x); % 1x5 vector, x input needs to be in [rad]. figure(2) plot(x,y,'-bx'), hold on xlabel('x [rad]') ylabel('y=sin(x)') s=x(2)-x(1); % step size, between points %% Area as typed into calculator, simpson vs trapez As_calc= s/3*(y(1) + 4*y(2) + 2*y(3) + 4*y(4) + y(5)) % y(ind) takes index from vector y At_calc= s/2*(y(1) + 2*y(2) + 2*y(3) + 2*y(4) + y(5)) % y(ind) takes index from vector y %% Area calculated using vector multiplication of factors with y-values sf= [1 4 2 4 1]; % Simpson factor vector trf=[1 2 2 2 1]; % Trapez factor vector As=s/3 * (sf*y') % Simpson rule, vector multiplication, y' transform necessary 1x5*5x1=1x1 % alternatively: %As=s/3 * sum(sf.*y) % Simpson rule, element-wise multiplication using .* At=s/2 * ( trf*y' ) % Trapez rule comparison %% Area calculated using built-in trapz and HiB developed simps function % Automatically adjusts length of sf and trf for different x, y input As_hib_fun=simps(x,y) % HiB developed function, on It's Learning At_matlab_fun = trapz(x,y) % Matlab Trapez built-in function % Parenthesis () is used after all built-in Matlab functions, type >>help trapz in Command window to see what input is needed %% Exact solution should be A = 2; decrease step size and trapz and simps % should move towards this value. x_fine = 0:pi/200:pi; y_fine = sin(x_fine); As_fine = simps(x_fine,y_fine) At_fine = trapz(x_fine,y_fine) %% Above can be used to calculate the area under any points y(x) even when % the function f(x) is not known. For a known function you can also define the % function and take the exact integral: F = @(x)sin(x); I_exact = integral(F,0,pi) disp('Conclusion: Simpson closer to exact result A=2 when using few points.') %% Example 2 on page 33-34 in Rawson&Tupper is a good way to repeat different % integration methods at home.