MATLAB Answers

Summing using simspons rule for a given range

17 views (last 30 days)
Oliver Wilson
Oliver Wilson on 9 Apr 2021 at 15:13
Answered: John D'Errico on 9 Apr 2021 at 17:33
I am aiming to use a composite simpsons rule on a function but am only interested in summing in when that function is less then a given value eg y = 10
function S=simpson_rule(f,x,dn)
while (f(x)>10)
f(x) = 0
h=(x(2)-x(1))/(2*dn); % finding column width
s1=0; %initialising series values
f1 = f(x(1)); %value of function at start
f2 = f(x(2)); %value of function at end
for k=1:dn % odd series
for k=1:(dn-1) %even series
S=h*(f1+f2+4*s1+2*s2)/3; %simpsons rule formula based on
This what ive got but it still sums values higher then y = 10
any advice welcome

Answers (2)

VBBV on 9 Apr 2021 at 15:35
%f true
if f(x)>10
f(x) = 0
... % rest of code
Try this
John D'Errico
John D'Errico on 9 Apr 2021 at 17:20
This won't work, at least because it is not even valid MATLAB code. f(x)=0 is NOT a valid way to assign a value in MATLAB.

Sign in to comment.

John D'Errico
John D'Errico on 9 Apr 2021 at 17:33
If I might suggest, your goal is actively a poor one. Why?
Simpson's rule is a higher order rule. It tries to give you a higher degree of accuracy. However, the idea of introducing what is essentially multiple points of non-differentiability into your function will kill any gains you would have achieved using the higher order nature of Simpson's rule. There is simply no purpose in using Simpson's rule on a function that is not well behaved to gain from the higher order.
So first, just use trapezoidal rule.
Next, are you asking to sum only the part of your function value that does not exceed 10? That is, if the function is larger than 10, will you just use 10 at that point? Or will you not integrate at all over any region where the function value is greater than 10? These two are VERY different goals, and will have very different results.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by