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

• To: mathgroup at smc.vnet.net
• Subject: [mg66307] Re: [mg66298] Re: Extract any diagonal from a square matrix...
• From: Sseziwa Mukasa <mukasa at jeol.com>
• Date: Tue, 9 May 2006 02:34:53 -0400 (EDT)
• References: <200605080446.AAA07438@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```On May 8, 2006, at 12:46 AM, Bill Rowe wrote:

> 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]
>
> [deleted]

> 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

I am also going to use this convention because it makes life simpler:

> d=
>
> 2 -- 2nd superdiagonal
> 1 -- 1st superdiagonal
> 0 --  main diagonal
> -1 -- 1st subdiagonal
> -2 -- 2nd subdiagonal

Separating it into two cases:

DiagonalT[a_?MatrixQ,d_?NonNegative]:=Table[a[[i,i+d]],{i,First
[Dimensions[a]]-d}]

DiagonalT[a_?MatrixQ,d_?Negative]:=Table[a[[i-d,i]],{i,First
[Dimensions[a]]+d}]

Regards,

Ssezi

```

• Prev by Date: License server issue
• Next by Date: two graphics questions and one general question
• Previous by thread: Re: Extract any diagonal from a square matrix...
• Next by thread: Re: Extract any diagonal from a square matrix...