updated to work for matrices of variable length