Simpsons 1/3 rule function not working
8 views (last 30 days)
Show older comments
I'm trying to do a simpsons 1/3 rule that you can break up an integration and run the rule on smaller segments to get a more accurate answer. It's fairly basic however when inputed as a function it only gives me the first x interation. When I run the code seperately it works perfect.
function [duck] = simp13(func, a, b, n)
%(b-a)/6 * f(x0) + 4f(x1) + f(x2)
if b <= a; error("b cannot be greater than a"); end
% n equals number of times rule is implimented
l = b-a;
c = l/(2*n);
xvals = a:c:b;
duck = 0;
count = 1;
for i = 1:n
duck = duck + (xvals(:,count + 2) - xvals(:,count))/6*(func(xvals(:,count)) + 4*func(xvals(:,count + 1)) + func(xvals(:,count + 2)));
count = count + 2;
end
end
0 Comments
Answers (1)
Alan Stevens
on 2 Apr 2025
Are you looking for something like this?
a = 1; b = 3;
f = @(x) exp(x);
n = 6;
Ysimp = simp13(f,a,b,n)
Yexact = exp(b)-exp(a)
function [duck] = simp13(func, a, b, n)
%(b-a)/6 * f(x0) + 4f(x1) + f(x2)
if b <= a; error("b cannot be greater than a"); end
% n equals number of times rule is implimented
l = b-a;
c = l/(2*n);
xvals = a:c:b;
duck = 0;
count = 1;
for i = 1:n
duck = duck + (xvals(:,count + 2) - xvals(:,count))/6*(func(xvals(:,count)) + 4*func(xvals(:,count + 1)) + func(xvals(:,count + 2)));
count = count + 2;
disp([count, duck])
end
end
0 Comments
See Also
Categories
Find more on Numerical Integration and Differential Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!