Integrating the volume of a sphere using a step function as an integrand
13 views (last 30 days)
Show older comments
My task is to calculate the volume of a sphere using the integral3 module in matlab.
My integration is over the cartezian (x,y,z) coordinates of a cube that contains my sphere. To only integrate over the x,y,z coordinates of the sphere inside the cube, I use a step function called "sphere" that returns the integrand 1 if the coordinates are inside or on the sphere, and 0 if they are outside the sphere.
However, I haven't been able to code this into something that does not return an error. Please help!
Here is my step function:
q = integral3(sphere,-1,1,-1,1,-1,1)
function t = sphere(x,y,z)
r0 = 1;
r1 = (x.^2+y.^2+z.^2).^0.5;
if r1 <= r0
t = 1;
else
t = 0;
end
end
However this returns the error:
Not enough input arguments.
Error in untitled>sphere (line 3)
r1 = (x.^2+y.^2+z.^2).^0.5;
I've also tried to use an anonymous function:
fun = @(x,y,z) sphere(x,y,z);
q = integral3(fun,-1,1,-1,1,-1,1)
But this also returns a bunch of errors:
Error using integral2Calc>integral2t/tensor (line 241)
Integrand output size does not match the input size.
Error in integral2Calc>integral2t (line 55)
[Qsub,esub] = tensor(thetaL,thetaR,phiB,phiT);
Error in integral2Calc (line 9)
[q,errbnd] = integral2t(fun,xmin,xmax,ymin,ymax,optionstruct);
Error in integral3>innerintegral (line 128)
Q1 = integral2Calc( ...
Error in integral3>@(x)innerintegral(x,fun,yminx,ymaxx,zminxy,zmaxxy,integral2options) (line 111)
f = @(x)innerintegral(x, fun, yminx, ymaxx, ...
Error in integralCalc/iterateScalarValued (line 314)
fx = FUN(t);
Error in integralCalc/vadapt (line 132)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen);
Error in integralCalc (line 75)
[q,errbnd] = vadapt(@AtoBInvTransform,interval);
Error in integral3 (line 113)
Q = integralCalc(f,xmin,xmax,integralOptions);
0 Comments
Accepted Answer
Matt J
on 6 Oct 2021
Edited: Matt J
on 6 Oct 2021
You won't be able to get very good accuracy integrating a step function because of its discontinuity. It would be better if you integrated in spherical coordinates where a step function is unnecessary. Regardless, here is how the code should look if you must integrate in Cartesian space.
r0=1;
fun=@(x,y,z)double(sqrt(x.^2+y.^2+z.^2)<=r0);
q = integral3(fun,-r0,r0,-r0,r0,-r0,r0,'AbsTol',1e-2)
4 Comments
Matt J
on 6 Oct 2021
You need to be doing element-wise division ./
Everything should be element-wise, for that matter.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!