Azzera filtri
Azzera filtri

How to Make Simpsons Rule UDF

2 visualizzazioni (ultimi 30 giorni)
Aren Arslanyan
Aren Arslanyan il 4 Ott 2020
Risposto: Mohith Kulkarni il 7 Ott 2020
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.

Risposte (1)

Mohith Kulkarni
Mohith Kulkarni il 7 Ott 2020
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)))

Categorie

Scopri di più su Numerical Integration and Differential Equations in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by