updated hopefully can work for all NxN matrices