Re: check if a square matrix is diagonal
- To: mathgroup at smc.vnet.net
- Subject: [mg115305] Re: check if a square matrix is diagonal
- From: Thomas Dowling <thomasgdowling at gmail.com>
- Date: Fri, 7 Jan 2011 04:08:57 -0500 (EST)
Hello,
Using your approach:
checkIfDiagonalMatrix[m_]:=Module[{d,mtemp},d=Dimensions[m];
mtemp=DiagonalMatrix[Diagonal[m]]-m;
If[mtemp==Array[0 &,Dimensions[m]],Print["True"],Print["False"]]]
or maybe...
checkIfDiagonalMatrix2[m_]:=Module[{d,mtemp},d=Dimensions[m];
mtemp=ReplacePart[m,{i_,i_}:>0];
If[mtemp==Array[0 &,Dimensions[m]],Print["True"],Print["False"]]]
For example:
mat=Array[Subscript[a,##]&,{4,4}];
diagmat=DiagonalMatrix[Diagonal@mat];
checkIfDiagonalMatrix[diagmat]
checkIfDiagonalMatrix2[mat]
You may be interested in the following link to an old thread (I almost wrote
'friend'!):
http://forums.wolfram.com/mathgroup/archive/1995/Aug/msg00153.html
Tom Dowling
On Thu, Jan 6, 2011 at 7:06 AM, 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]
> ]
>
>