Fermat’s theorem for matrices