How do I numerically integrate using the composite trapezoidal rule in Matlab?
11 views (last 30 days)
Show older comments
A problem I have to solve:
Write and submit a generic function for computing a numerical integral of a variable y using the composite trapezoidal rule. Use two input variables, x and y, where both are identically sized arrays. The variable y should represent the function you want to integrate evaluated at the points defined in x.
I am not very gifted in using Matlab syntax or numerical approximation. Can someone edit my code or help me understand how to solve this problem?
My code:
function[AreaT]=comptrap(x,y)
b=x(end)
a=x(1)
term2=0
for i=2(length(y)-1)
term2=term2+y(i);
end
h=(b-a)/(length(x)-1)
AreaT=(h/2)*(y(1))+2*term2+y(end);
Please help, Thanks
0 Comments
Answers (1)
Swastik Sarkar
on 15 Oct 2024
The implementation of the composite trapezoid rule appears correct. Below is an enhanced version of the code that includes handling for edge cases and utilizes vectorization for summing terms:
function [AreaT] = comptrap(x, y)
if length(x) ~= length(y)
error('x and y must be vectors of the same length.');
end
n = length(x) - 1;
h = (x(end) - x(1)) / n;
term2 = sum(y(2:n));
AreaT = (h / 2) * (y(1) + 2 * term2 + y(end));
end
Hope this helps.
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!