Thanks a lot! Amazing to see how much these few lines of code can be improved.
Thanks for pointing out that trace also works for non-square matrices (the mathematician in me assumed that trace only works for square matrices). I will try to implement this.
Edit: I see. It already works for non-square matrices. Thanks a lot.