Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2006
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2006

[Date Index] [Thread Index] [Author Index]

Search the Archive

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

  • To: mathgroup at smc.vnet.net
  • Subject: [mg66298] Re: Extract any diagonal from a square matrix...
  • From: Bill Rowe <readnewsciv at earthlink.net>
  • Date: Mon, 8 May 2006 00:46:42 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

On 5/6/06 at 11:50 PM, rson at new.rr.com (hawkmoon269) 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

Another possible approach would be to use SparseArray. For example, the 1st superdiagonal can be obtained as follows:

In[21]:=
a=Table[10i +j,{i,4},{j,4}];
b=SparseArray[{i_,j_}:>1/;j==i+1,{4,4}];
SparseArray[a b]/.SparseArray[_,_,_,a_]:>Last@a

Out[23]=
{12,23,34}

This can be generalized to extract an arbitrary diagonal by changing b to be

b=SparseArray[{i_,j_}:>1/;j==i+d] where d=

2 -- 2nd superdiagonal
1 -- 1st superdiagonal
0 --  main diagonal
-1 -- 1st subdiagonal
-2 -- 2nd subdiagonal
--
To reply via email subtract one hundred and four


  • Prev by Date: Re: Intersection of Conic Sections
  • Next by Date: Re: General--Differential equation problem..
  • Previous by thread: Re: Extract any diagonal from a square matrix...
  • Next by thread: Re: Re: Extract any diagonal from a square matrix...