Fixed matrix being generated in transposed order.

Performance goes down.
Use ST monad to build result in place.