%% 4-D Integral of Sphere
% Use nested calls to integral3 and integral to calculate the volume of a 4-D sphere.
% The volume of a 4-D sphere of radius r is
% V_4 \left(r\right)=\int_0^{2\pi } \int_0^{\pi } \int_0^{\pi } \int_0^r r^3 \;\sin^2 \left(\theta \right)\;\sin \left(\phi \right)\;\textrm{dr}\;d\theta \;d\phi \;d\xi \ldotp
% The integral quadrature functions in MATLAB® directly support 1-D, 2-D, and 3-D integrations. However, to solve 4-D and higher order integrals, you need to nest calls to the solvers.
%
% Create a function handle f\left(r,\theta ,\phi ,\xi \right) for the integrand using element-wise operators (.^ and .*).

f = @(r,theta,phi,xi) r.^3 .* sin(theta).^2 .* sin(phi);

%
% Next, create a function handle that calculates three of the integrals using integral3.

Q = @(r) integral3(@(theta,phi,xi) f(r,theta,phi,xi),0,pi,0,pi,0,2*pi);

%
% Finally, use Q as the integrand in a call to integral. Solving this integral requires choosing a value for the radius r, so use r=2.

I = integral(Q,0,2,'ArrayValued',true)

% The exact answer is \frac{\pi^2 r^4 }{2\;\Gamma \left(2\right)}.

I_exact = pi^2*2^4/(2*gamma(2))

% Copyright 2018 The MathWorks, Inc.