Re: [S] Q: How to sum the diagonals of a matrix?

Franz-Josef Mueter (mueter@halibut.ims.uaf.edu)
Thu, 19 Mar 1998 16:35:18 -0900 (AKST)


A simple way to do it is to use row(x)+col(x), which will return
appropriate indices, with tapply:

> x <- matrix(1:20,4)
> x
[,1] [,2] [,3] [,4] [,5]
[1,] 1 5 9 13 17
[2,] 2 6 10 14 18
[3,] 3 7 11 15 19
[4,] 4 8 12 16 20

> tapply(x,col(x)+row(x),sum)
2 3 4 5 6 7 8 9
1 7 18 34 50 45 35 20

will give the desired result

Franz Mueter

***************************************************************
Franz-Josef Mueter | Voice: (907) 474-7839
Institute of Marine Sciences | (907) 479-8815
School of Fisheries and Ocean Sciences | Fax: (907) 474-1943
University of Alaska | e-mail:
Fairbanks, Alaska, 99709-1080 | mueter@ims.alaska.edu
---------------------------------------------------------------

-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news