Re: [R] Matrix Indexing

From: Duncan Murdoch <murdoch_at_stats.uwo.ca>
Date: Sat, 12 Apr 2008 07:01:05 -0400

Rory Winston wrote:
> Hi
>
> Does anyone know how I might pick out diagonal elements of a matrix using a
> vector?
>
> If I create a matrix a:
>
> a <- matrix(c(1:16), 4, byrow=TRUE)
>
> and I want to pick out the elements (1,1),(2,2),(3,3), or another arbitrary
> diagonal (upper or lower), is there any way I can use a vector to do this?
> So if I want a diagonal of size 3, I could create a vector like x <- c(0:2)
> and then pick out a[1+x,1+x]? Currently, using a vector in this way gives me
> a sub-matrix, as I get the cartesian product of the indexes (which is to be
> expected, as I guess I am misusing the vector notion here).
>
> Anyone know how to do this?
>
diag() is what you want, as others have said.

For more general cases, you can also consider matrix indexing using two columns of indices:

 > diag(a)
[1] 1 6 11 16
 > x <- 0:2
 > a[cbind(1 + x, 1 + x)]
[1] 1 6 11

Duncan Murdoch
> Cheers
> Rory
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Sat 12 Apr 2008 - 11:06:57 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 12 Apr 2008 - 13:30:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive