Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a 5x5 matrix with 0's lined diagonally

Tags:

In R, I want create a 5x5 matrix of 0,1,3,5,7 such that:

     0    1    3    5    7       1    0    3    5    7       1    3    0    5    7        1    3    5    0    7        1    3    5    7    0 

So obviously I can generate the starting matrix:

    z <- c(0,1,3,5,7)     matrix(z, ncol=5, nrow=5, byrow = TRUE) 

but I'm unsure of how to move the 0's position. I'm sure I have to use some sort of for/in loop, but I really don't know what exactly I need to do.

like image 722
Paul Avatar asked Jun 02 '16 19:06

Paul


1 Answers

How about this:

m <- 1 - diag(5) m[m==1] <- rep(c(1,3,5,7), each=5) m #      [,1] [,2] [,3] [,4] [,5] # [1,]    0    1    3    5    7 # [2,]    1    0    3    5    7 # [3,]    1    3    0    5    7 # [4,]    1    3    5    0    7 # [5,]    1    3    5    7    0 
like image 60
Josh O'Brien Avatar answered Sep 22 '22 01:09

Josh O'Brien