Optimized matrix calculation