How to perform differentiations on matrices