Re: RealDigits
- To: mathgroup at christensen.cybernetics.net
- Subject: [mg1840] Re: [mg1741] RealDigits
- From: Count Dracula <lk3a at kelvin.seas.virginia.edu>
- Date: Mon, 7 Aug 1995 20:25:08 -0400
- Organization: University of Virginia
In Article: 1118 of comp.soft-sys.math.mathematica
wagner at bullwinkle.cs.Colorado.EDU (Dave Wagner) writes:
> MapIndexed. It turns out to be
> the perfect function for checking a matrix to see if it satisfies a
> certain form. For example, the following function checks a matrix
> to see if it is diagonal:
> DiagonalQ[m_] :=
> And @@ Flatten[ MapIndexed[ #1==0 || Equal @@ #2 &, m, {2} ]]
MapIndexed used like this is far from being the perfect function
for this task. This is a very inefficient way to check if a
matrix is diagonal. The best way will probably use a method
that stops at the first encounter with one nonzero nondiagonal
element. But even the naive function below is faster than
DiagonalQ :
diagonalQ[m_?MatrixQ] :=
Block[{n, row},
n = Length[m];
row = Table[0, {n - 1}];
And @@ Map[Equal[#1, row]&, MapThread[Drop, {m, Partition[Range[n], 1]}]]
] /; SameQ @@ Dimensions[m]
mat = DiagonalMatrix[Range[150]]
test := {Timing[diagonalQ[mat]], Timing[DiagonalQ[mat]]}
Test run on an IBM RS6000:
In[6]:= test
Out[6]= {{0.11 Second, True}, {3.57 Second, True}}
--
___________________________________________________________________________________
Levent Kitis lk3a at cars.mech.virginia.edu lk3a at kelvin.seas.virginia.edu
University of Virginia Department of Mechanical, Aerospace, and Nuclear Engineering