# Archive for category Uncategorized

### Hyperspherical Coordinates

Suppose we have a vector ${\bf x}=(x_1,x_2,\ldots,x_n)^\prime \in \mathbb{R}^n$ residing in an $n$-dimensional Euclidean space. How do we express this vector using (hyper-)spherical coordinates in MATLAB? MATLAB implements a couple of functions, namely cart2pol() and cart2sph() , that handle the conversion in two and three dimensions, respectively. However, there is no general method for vectors of arbitrary dimension.

Fortunately, Wikipedia lists the formulas required to convert Euclidean coordinates to hyperspherical coordinates and these are relatively straightforward to implement in MATLAB. Below is a MATLAB function that takes an $n$-dimensional Euclidean vector as input and returns the corresponding radial coordinate $r > 0$ as well as the $(n-1)$ angular coordinates $\phi_1, \phi_2, \ldots, \phi_{n-1}$; note that, $\phi_{n-1} \in [0,2\pi]$, while all the other angles are in the set $[0, \pi]$.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 %% The input vector x is a n-dim. column vector. function [r,theta]=cart2nsph(x)   %% setup n = length(x); theta = zeros(n-1,1); x2 = x.^2; cumx = cumsum(x2(end:-1:2));   %% Compute the radial coordinate r = sqrt(sum(x2));   %% Compute the angles theta(1:end-1,1) = x(1:end-2,1) ./ sqrt( cumx(end:-1:2) ) ; theta(end,1) = (sqrt(sum(x2(end:-1:end-1,1))) + x(end-1,1)) ./ x(end,1); theta = acot(theta); theta(theta<0) = theta(theta<0)+pi; % Convert acot principal value to [0,pi] theta(end,1) = 2*theta(end,1); % Last angle is between [0,2pi]   %% done return;

Line 11 computes the radial coordinate which is simply the square root of the sum of the squares of the original, Euclidean coordinates. Lines 14-18 are required to obtain the angular coordinates. Some care is necessary in order to get all the angles in the correct range, since the principal value of the function acot() in MATLAB is in $[-\pi/2,\pi/2]$ and not in the (usual) range of $[0,\pi]$. We correct for this in Line 17 by adding $\pi$ to all the “negative” angles.

The function to compute $n$-dimensional Euclidean coordinates from hyperspherical coordinates is somewhat simpler. One possible implementation is given below:

1 2 3 4 5 6 7 8 9 10 11 12 %% Radial coordinate, r>0, must be positive. %% The angles theta_1,...,theta_{n-2} must be in [0,pi], while %% theta_{n-1} should be in [0,2pi]. function x = nsph2cart(r,theta)   c=[cos(theta); 1]; s=[1 ;cumprod(sin(theta))];   x=r*(c.*s);   %% done return;

Except in some special cases the transform is unique. Both functions were tested on MATLAB version 7.12.0 (R2011a) and dont have any error checking. I hope that some of you can find these functions useful in your work.