Second version (tested with matrix (1,2,3,4))