fix index exceeds matrix dimension issue.