How to Make Simpsons Rule UDF
조회 수: 2 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
답변 (1개)
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)))
댓글 수: 0
참고 항목
카테고리
Help Center 및 File 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!