[R] setting off-diagonals to zero

David Winsemius dwinsemius at comcast.net
Thu Jan 24 02:31:06 CET 2013

On Jan 23, 2013, at 7:13 AM, emorway wrote:

> The following 1460 x 1460 matrix can be throught of as 16 distinct 365 x 365
> matrices.  I'm trying to set off-diaganol terms in the 16 sub-matrices with
> indices more than +/- 5 (days) from each other to zero using some for loops.
> This works well for some, but not all, of the for loops.  The R code I"m
> using follows.  For some reason the third loop below zero's-out everything
> in the sub-quadrant it is targeting, which is readily observable when
> viewing the matrix ("View(MAT)").
>
> library(Matrix)
> MAT<-matrix(rnorm(1460*1460,mean=0,sd=1),nrow = 1460, ncol = 1460)
>

The way to do that in a single 365 x 365 matrix is:

Mat <- matrix( 1:(365*365), 365, 365)
Mat[ abs( col(Mat)-row(Mat) ) > 5 ] <- 0
Mat

The way to propagate that pattern is to use rep(), so here is a one-liner for the task:

MAT[ rep( abs( col(Mat)-row(Mat) ) > 5, 16) ] <- 0

Didn't test on you gigantuan matrix;  used smaller example:

Mat <- matrix( 1:(16*16), 16, 16)
test <- rbind(Mat, Mat)
test[rep( abs( col(Mat)-row(Mat) ) > 2 , 2)] <- 0
test

--
David.

> #works great
> for (i in 1:365) {
>  SEQ <- (i - 5):(i + 5)
>  SEQ <- SEQ[SEQ > 0 & SEQ < 366]
>  MAT[(1:365)[-SEQ], i] <- 0
> }
>
> #works great
> for (i in 1:365) {
>  SEQ <- (i - 5):(i + 5)
>  SEQ <- SEQ[SEQ > 0 & SEQ < 366]
>  MAT[(1:365)[-SEQ], i + 365] <- 0
> }
>
> #zero's out everything, including main-diagonal and near-main-diagonal
> terms???
> for (i in 731:1095) {
>  SEQ <- (i - 5):(i + 5)
>  SEQ <- SEQ[SEQ > 730 & SEQ < 1096]
>  MAT[(731:1095)[-SEQ], i + 365] <- 0
> }
>
> View(MAT)
>
> I'm not sure why the third FOR loop above is not leaving the main-diagonal
> and near-main-diagonal terms alone?
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/setting-off-diagonals-to-zero-tp4656407.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.

David Winsemius
Alameda, CA, USA

More information about the R-help mailing list