Replaced loops with matrix algebra