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
- Follow-Ups:
- Re: Re: Extract any diagonal from a square matrix...
- From: Sseziwa Mukasa <mukasa@jeol.com>
- Re: Re: Extract any diagonal from a square matrix...