How to Make Simpsons Rule UDF

2 次查看(过去 30 天)
Aren Arslanyan
Aren Arslanyan 2020-10-4
function output = Simpsons(f,a,b,h)
% f - funtion
% a - This is the initial x value
% b - This is the final x value
% h - This is the step-size
x=[a:h:b]; %need to create a vector of n+1 evenly spaced points
sr=(h/3)*(f(x(1))+2*sum(f(x(3:2:end-2)))+4*sum(f(x(2:2:end)))+f(x(end)))
output=sr
end
I made this simpsons rule UDF and it works can someone just explain wihat the last line reads? I don't fully understand it. Also please let me know if this is a valid UDF for Simpsons if you do not see any errors.

回答(1 个)

Mohith Kulkarni
Mohith Kulkarni 2020-10-7
It is a valid simpsons rule implementation. Let me break the line down.
sr=(h/3)*(f(x(1))+2*sum(f(x(3:2:end-2)))+4*sum(f(x(2:2:end)))+f(x(end)))
This expression above is equivalent to (Δx/3)*[f(x0)+4f(x1)+2f(x2)+4f(x3)+2f(x4)+⋯+4f(xn−1)+f(xn)].
x(3:2:end-2) %j:i:k creates a regularly-spaced vector using i as the increment between elements.
So here indexing into the elements of x at odd places. We left out the end as f(xn) is multiplied with 1 and not 2. Similarly, access elements of x at even positions using
x(2:2:end)
Since we are passing a vector to f, the ouput is a vector and sum is used to find the sum of the output vector.
sum(f(x(3:2:end-2)))

类别

Help CenterFile Exchange 中查找有关 Numerical Integration and Differential Equations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by