Fix a couple of crashes with empty matrices. Some small optimisations.