# [MATLAB] Spherical Harmonics

Tags:
1. Jul 31, 2014

### t14g0

Hey guys, This is my first post here, so I will apologize in advance in case I'm posting this in the wrong section.

I wrote a very simple function to calculate spherical harmonics in matla, and I used this function during 3 years. Yesterday I found that the fucntion was actually wrong, and looking up on matlab function database I realised that EVERY implementation were wrong.

This is the code i use, and is very similar to the rest of the codes I found online:

function Y = spherical_harmonic(l,m,THETA,PHI)

Lmn=legendre(l,cos(THETA),'norm');
mm = m;
m = abs(m);

if l~=0
Lmn=squeeze(Lmn(m+1,:,;
end

C=(-1)^m / sqrt(2*pi);
Y = C * Lmn .* exp(i*m*PHI);

if mm<0
Y = (-1)^m * conj(Y);
end​

Let me exemplify one test: if you try to find the spherical harmonics for m=1, l=1, theta = pi/2 and phi = 0 it will give the correct answer (-0.3455). Now try to find the spherical harmonics for m=1, l=1, theta = - pi/2 and phi = 0, it will give you the same answer (-0.3455). But the correct answer is (0.3455). You can verify this by getting the closed formula solution for the spherical harmonics of l=1 and m=1 (sine dependent).

The thing is, using the implementation given by matlab of the legendre function the cosine of theta will always be squared. The correct way to implement this was to replace 1-cos(theta)^2 for sine(theta)^2, and do the rest of the operations. But for this I would have to implement the spherical harmonics using a symbolic language. Mathematica does this way, and always gives you the correct values (I don't know if they have a table with the closed formula solution for every combination of l and m, or if they do some magical trick inside, but the thing is, they version of the code works).

I don't know how to make it right, does anyone have any tips for me?

P.S: I know of a LOT of people who uses matlab to compute spherical harmonics and published a lot of papers with their code. I wonder if this "error" had some implications with the results.

2. Aug 7, 2014

### Staff: Mentor

These are spherical coordinates, so the range of $\theta$ is $[0, \pi]$.