How do I calculate a matrix with conditions?