function [x, y, z] = sph2rect(r, theta, phi)
%sph2rect Convert from spherical to rectangular coordinates.
%    [x y z] = sph2rect(r,theta,phi) returns Cartesian coordinates
%    sufficient for graphing with surf.

[n, p] = size(r);
x = zeros(n,n);
y = zeros(n,n);
z = zeros(n,n);
u = zeros(3,1);
v = zeros(3,1);
P = zeros(3,3);
for i = 1:n
   for j = 1:p
      P = [sin(theta(i,j))*cos(phi(i,j)) cos(theta(i,j))*cos(phi(i,j)) -sin(phi(i,j));
                  sin(theta(i,j))*sin(phi(i,j)) cos(theta(i,j))*sin(phi(i,j))  cos(phi(i,j));
                  cos(theta(i,j))          -sin(theta(i,j))                0];
      v = [r(i,j) theta(i,j) phi(i,j)]';
      u = P*v;
      x(i,j) = u(1);
      y(i,j) = u(2);
      z(i,j) = u(3);
   end
end
