       Re: check if a square matrix is diagonal

• To: mathgroup at smc.vnet.net
• Subject: [mg115329] Re: check if a square matrix is diagonal
• From: Bob Hanlon <hanlonr at cox.net>
• Date: Fri, 7 Jan 2011 04:13:36 -0500 (EST)

```m = DiagonalMatrix[Range]

{{1, 0, 0}, {0, 2, 0}, {0, 0, 3}}

Note that Dimensions[m] is a list not a number

d = Dimensions[m]

{3, 3}

Select a part

d = Dimensions[m][]

3

You can simplify your Table build

Table[Table[0, {i, 1, d}], {i, 1, d}] ==
Table[0, {i, 1, d}, {i, 1, d}] ==
Table[0, {d}, {d}]

True

An If statement is not needed if you are just going to return the boolean

You should also use SetDelayed ( := ) rather than Set ( = )

Clear[checkIfDiagonalMatrix]

checkIfDiagonalMatrix[m_] := Module[{d, mtemp},
d = Dimensions[m][];
mtemp = DiagonalMatrix[Diagonal[m]] - m;
mtemp == Table[0, {d}, {d}]]

checkIfDiagonalMatrix[m]

True

Bob Hanlon

---- benyaya <xiaochu at gmail.com> wrote:

=============
What I try to do is extract the diagonal, subtract if from the matrix,
then compare the new matrix with 0.
My code doesn't work out though, can anyone help? thanks a lot.

checkIfDiagonalMatrix[m_] = Module[{d, mtemp},
d = Dimensions[m];
mtemp = DiagonalMatrix[Diagonal[m]] - m;
If[mtemp == Table[Table[0, {i, 1, d}], {i, 1, d}],
True,
False]
]

```

• Prev by Date: Re: FillingStyle -> Striped ?
• Next by Date: Extracting pixel values from an image under a polygon (region of interest)
• Previous by thread: Re: check if a square matrix is diagonal
• Next by thread: Re: check if a square matrix is diagonal