MATLAB code for magnetic fields