Skip to content
Prev 315992 / 398513 Next

setting off-diagonals to zero

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

            
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