2.13 Check if a Matrix is diagonal

A diagonal matrix is one which has only zero elements off the diagonal. The Mathematica code was contributed by Jon McLoone.

Mathematica

diagonalQ[m_List]/;ArrayDepth[m]===2&&Equal@@Dimensions[m]:= 
  And@@Flatten[MapIndexed[#1===0||Equal@@#2&,m,{2}]]; 
 
diagonalQ[m_]:=Return[False]; 
matA = {{1, 2}, 
        {2, 4}}; 
 
matB = {{1, 0}, 
        {0, 2}}; 
 
matC = {{1, 0, 2}, 
        {0, 2, 4}}; 
 
diagonalQ[matA] 
diagonalQ[matB] 
diagonalQ[matC]
 

  Out[59]= False 
  Out[60]= True 
  Out[61]= False
 

 

Maple

A:=Matrix([[1,0],[0,2]]); 
Student:-NumericalAnalysis:-IsMatrixShape(A,'diagonal');
 

true