Don't know what is wrong with this double integral code
3 次查看(过去 30 天)
显示 更早的评论
I'm trying to write a script that can calculate the double integral of a function. What I want to do is this:
- move along the y-axis.
- for each value of y, I calculate the area of the cross-section of the 3D graph, which is the integral of the function for x at that specific value of y.
- I multiply this area by a small increment in y to get an elemental volume.
- I add up all these volumes up to get the final volume under the graph, which is equal to the double integral.
I don't know why my code isn't giving me the write answer for sin(x)*sin(y) between 0 and pi for x limits and 0 and pi for y limits.
I attach my code as a .m file and also below:
f = @(a, b) sin(a)*sin(b);
x0 = 0;
xn = pi; % Integral limits
n = 1000*pi; % No. intervals for x
y0 = 0;
ym = pi; % Integral limits
m = 1000*pi; % No. intervals for y
hx = (xn - x0)/n; % x step size
hy = (ym - y0)/m; % y step size
I = 0;
for y = y0:hy:ym
A = 0;
for x = x0:hx:xn
A = A + hx*f(x,y);
A = A - 0.5*hx*(f(x0,y) + f(xn,y));
I = I + A*hy;
end
end
0 个评论
回答(1 个)
另请参阅
类别
在 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!