Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2011

[Date Index] [Thread Index] [Author Index]

Search the Archive

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[1]:= m = RandomReal[1, {10000, 10000}];

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

Out[2]= {2.51418,False}

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

Out[3]= {1.09644,False}

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

Out[4]= {0.770909,False}

But for a diagonal matrix

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

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

Out[6]= {0.099239,True}

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

Out[7]= {0.049362,True}

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

Out[9]= {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