Do a quick test: replace mdist=mahadistance(icovar,meanmat,pixel); with mdist=0;
If it works fast, your problem is in mahadistance function. If you post that, someone might find a way to make it faster
Sorry, I noticed you posted it already. But please check your speed with mdist=0; Also, you can comment out line by line, see where is your problem.