Re: RealDigits
- To: mathgroup at christensen.cybernetics.net
- Subject: [mg1844] Re: [mg1741] RealDigits
- From: wagner at bullwinkle.cs.Colorado.EDU (Dave Wagner)
- Date: Mon, 7 Aug 1995 20:25:51 -0400
- Organization: University of Colorado, Boulder
In article <DCouH6.8tI at wri.com>, Count Dracula <lk3a at kelvin.seas.virginia.edu> wrote: >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. I said, "perfect... for checking a matrix to see if it satisfies a certain form." I wasn't limiting myself to checking for diagonality, which is something of a straw-man, as there are many different ways to optimize it. Doubtless you could also come up with more efficient (though not necessarily more understandable) functions for checking the other conditions that I mentioned, such as lower- and upper-triangular, etc. But MapIndexed provides a unifying framework for all of these, and in that sense it's "perfect". >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. True, this is a problem in general with the "And @@ Map[...]" paradigm. A better way to do that kind of thing is with Scan. But this isn't the reason for the slowness of the given function in the test case you used (a matrix that actually is diagonal). Truthfully, I was surprised at how slow it was. >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] I'd hardly call that function naive; I stand by the statement above, which is that MapIndexed provides an easy-to-understand way to solve an entire class of problems in an essentially similar way. Which, lest anyone forget, was simply a response to an earlier post questioning what in the world MapIndexed could possibly be used for. Dave Wagner Principia Consulting (303) 786-8371 dbwagner at princon.com http://www.princon.com/princon