Skip to content

Instantly share code, notes, and snippets.

@SergKolo
Created October 13, 2018 17:43
Show Gist options
  • Save SergKolo/86158edcf88f8cb5afcc78143f86c32c to your computer and use it in GitHub Desktop.
Save SergKolo/86158edcf88f8cb5afcc78143f86c32c to your computer and use it in GitHub Desktop.
simpsons rule in torture language called Matlab
function S_n = simpsons(x,f_x)
fprintf("FOURS LOOP\n");
n = length(x)-1;
h = (x(length(x)) - x(1))/n;
%h = (x(n_els) - x(1))/n_els
% gather all terms multiplied by 4
fours = 0;
for i = 2:2:length(x)-1
fprintf("i:%d | x(i): %f | f_x: %f | 4*f_x: %f \n",i,x(i),f_x(x(i)),4*f_x(x(i)));
fours = fours + 4*f_x(x(i));
end
fours
% gather all terms multiplied by 2
fprintf("TWOS LOOP");
x
twos = 0;
for i = 3:2:length(x)-2
fprintf("i:%d | x(i): %f | f_x: %f | 4*f_x: %f \n",i,x(i),f_x(x(i)),2*f_x(x(i)));
twos = twos + 2*f_x(x(i));
end
twos
fprintf("END LOOP")
S_n = (h/3) * ( f_x(x(1)) + fours + twos + f_x(x(length(x))) );
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment