I was taught that in a magnetic field $\vec B$, a current carrying loop with a magnetic moment $\vec M$, the loop experiences a torque given by $\tau=\vec M\times\vec B$. Further, the associated energy is given by (as in the electrical case by integrating $\tau d\theta$) $U(\theta)=-\vec M\cdot \vec B$. Now I had learnt that magnetic field cannot do any work (force and velocity are always perpendicular).
So,how are we associating an energy here? Where does this energy $U(\theta)$ come from? I can't account for it.