       Re: check if a square matrix is diagonal

• To: mathgroup at smc.vnet.net
• Subject: [mg115366] Re: check if a square matrix is diagonal
• From: Bill Rowe <readnews at sbcglobal.net>
• Date: Sun, 9 Jan 2011 02:17:54 -0500 (EST)

```On 1/8/11 at 3:39 AM, akoz at mimuw.edu.pl (Andrzej Kozlowski) wrote:

>An simpler approach is:

>diagonalQ[m_] := UpperTriangularize[m] = LowerTriangularize[m]

>This is slower for diagonal matrices but very much faster for
>non-diagonal ones.

Even simpler is the suggestion Dr Bob made:

m==DiagonalMatrix[Diagonal@m]

And after I had made my post I thought of something else that
seems fast which is

Total[Unitize@m,2]==Total[Unitize@Diagonal[m]]

It terms of speed for non-diagonal matrices, the simple method
suggested by Dr Bob is the fastest

In:= m = RandomReal[1, {10000, 10000}];

In:= Timing[UpperTriangularize[m] == LowerTriangularize[m]]

Out= {2.51418,False}

In:= Timing[Total[Unitize@m, 2] == Total[Unitize@Diagonal[m]]]

Out= {1.09644,False}

In:= Timing[m == DiagonalMatrix[Diagonal@m]]

Out= {0.770909,False}

But for a diagonal matrix

In:= m = SparseArray[Band[{1, 1}] -> RandomReal[1, {10000}]];

In:= Timing[UpperTriangularize[m] == LowerTriangularize[m]]

Out= {0.099239,True}

In:= Timing[Total[Unitize@m, 2] == Total[Unitize@Diagonal[m]]]

Out= {0.049362,True}

In:= Timing[m == DiagonalMatrix[Diagonal@m]]

Out= {0.067637,True}

It appears using Total and Unitize to count the non-zero entries
of m is faster.

it would seem

```

• Prev by Date: Re: Astronomical question
• Next by Date: Re: Mathematica will be a new feature of HTML6
• Previous by thread: Re: check if a square matrix is diagonal
• Next by thread: Re: check if a square matrix is diagonal