Copy the code for mean and rewrite for matirx