Optimize matrices calculation.