Re: Extract any diagonal from a square matrix...

*To*: mathgroup at smc.vnet.net*Subject*: [mg66398] Re: Extract any diagonal from a square matrix...*From*: Paul Abbott <paul at physics.uwa.edu.au>*Date*: Thu, 11 May 2006 02:16:09 -0400 (EDT)*Organization*: The University of Western Australia*References*: <e3js8r$8kh$1@smc.vnet.net>*Sender*: owner-wri-mathgroup at wolfram.com

In article <e3js8r$8kh$1 at smc.vnet.net>, "hawkmoon269" <rson at new.rr.com> wrote: > Trying to put a function together that extracts any one of the > diagonals from a square matrix. Right now I have this -- > > DiagonalT[a_List, d_Integer] := > Tr[Take[Which[Positive[d], a, Negative[d], Transpose[a]], > {1, Length[a] - Abs[d] + 1}, {Abs[d], Length[a]}], List] > > This works, but I thought there might be something less cumbersome. > Essentially, the function constructs a submatrix of the matrix so that > the requested diagonal from the matrix becomes the main diagonal of the > submatrix, which is then retrieved. D is the diagonal to retrieve, > where d = > > 3 -- 2nd superdiagonal > 2 -- 1st superdiagonal > 1 -- main diagonal > -2 -- 1st subdiagonal > -3 -- 2nd subdiagonal > > etc... > > Some other things I've considered -- > > ...rotating the elements of each row until column 1 becomes the > requested diagonal; Along these lines you can use MapIndexed: RotateRight /@ MapIndexed[RotateLeft, m] > ...dropping elements from each row until the first or last element in > each row becomes the next element in the requested diagonal; > ...flattening the matrix and then using Range and Part to retrieve the > requested diagonal. Defining Diagonals[m_] := MapIndexed[Take[#1, #2[[1]]] &, Reverse[Transpose[RotateRight /@ MapIndexed[RotateLeft, m]]]] then for square matrices, Reverse @ Diagonals[m] gives the list of superdiagonals, and Diagonals[Transpose[m]] gives the list of subdiagonals. Cheers, Paul _______________________________________________________________________ Paul Abbott Phone: 61 8 6488 2734 School of Physics, M013 Fax: +61 8 6488 1014 The University of Western Australia (CRICOS Provider No 00126G) AUSTRALIA http://physics.uwa.edu.au/~paul