diff scripts/general/sph2cart.m @ 8533:fb1b87ea4af9

Permit scalars when transforming coordinates.
author Ben Abbott <bpabbott@mac.com>
date Sat, 17 Jan 2009 17:32:11 -0500
parents a1dbe9d80eee
children eb63fbe60fab
line wrap: on
line diff
--- a/scripts/general/sph2cart.m	Sat Jan 17 11:41:25 2009 -0500
+++ b/scripts/general/sph2cart.m	Sat Jan 17 17:32:11 2009 -0500
@@ -19,7 +19,7 @@
 ## -*- texinfo -*-
 ## @deftypefn {Function File} {[@var{x}, @var{y}, @var{z}] =} sph2cart (@var{theta}, @var{phi}, @var{r})
 ## Transform spherical to cartesian coordinates.
-## @var{x}, @var{y} and @var{z} must be of same shape.
+## @var{x}, @var{y} and @var{z} must be of same shape, or scalar.
 ## @var{theta} describes the angle relative to the x-axis.
 ## @var{phi} is the angle relative to the xy-plane.
 ## @var{r} is the distance to the origin (0, 0, 0).
@@ -29,20 +29,60 @@
 ## Author: Kai Habel <kai.habel@gmx.de>
 ## Adapted-by: jwe
 
-function [X, Y, Z] = sph2cart (Theta, Phi, R)
+function [x, y, z] = sph2cart (theta, phi, r)
 
   if (nargin != 3)
     print_usage ();
   endif
 
-  if ((! (ismatrix (Theta) && ismatrix (Phi) && ismatrix (R)))
-      || (! size_equal (Theta, Phi))
-      || (! size_equal (Theta, R)))
-    error ("sph2cart: arguments must be matrices of same size");
+  if ((ismatrix (theta) && ismatrix (phi) && ismatrix (r))
+      && (size_equal (theta, phi) || isscalar (theta) || isscalar (phi))
+      && (size_equal (theta, r) || isscalar (theta) || isscalar (r))
+      && (size_equal (phi, r) || isscalar (phi) || isscalar (r)))
+
+    x = r .* cos (phi) .* cos (theta);
+    y = r .* cos (phi) .* sin (theta);
+    z = r .* sin (phi);
+
+  else
+    error ("sph2cart: arguments must be matrices of same size, or scalar");
   endif
 
-  X = R .* cos (Phi) .* cos (Theta);
-  Y = R .* cos (Phi) .* sin (Theta);
-  Z = R .* sin (Phi);
+endfunction
+
+%!test
+%! t = [0, 0, 0];
+%! p = [0, 0, 0];
+%! r = [0, 1, 2];
+%! [x, y, z] = sph2cart (t, p, r);
+%! assert (x, r);
+%! assert (y, [0, 0, 0]);
+%! assert (z, [0, 0, 0]);
 
-endfunction
+%!test
+%! t = 0;
+%! p = [0, 0, 0];
+%! r = [0, 1, 2];
+%! [x, y, z] = sph2cart (t, p, r);
+%! assert (x, r);
+%! assert (y, [0, 0, 0]);
+%! assert (z, [0, 0, 0]);
+
+%!test
+%! t = [0, 0, 0];
+%! p = 0;
+%! r = [0, 1, 2];
+%! [x, y, z] = sph2cart (t, p, r);
+%! assert (x, r);
+%! assert (y, [0, 0, 0]);
+%! assert (z, [0, 0, 0]);
+
+%!test
+%! t = [0, 0.5, 1]*pi;
+%! p = [0, 0, 0];
+%! r = 1;
+%! [x, y, z] = sph2cart (t, p, r);
+%! assert (x, [1, 0, -1], eps);
+%! assert (y, [0, 1, 0], eps);
+%! assert (z, [0, 0, 0], eps);
+