Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a matrix with four 1's in each row staggered

How can I easily create this matrix using clever commands:

1 0 0
1 0 0
1 0 0
1 0 0
0 1 0 
0 1 0
0 1 0 
0 1 0 
0 0 1
0 0 1
0 0 1
0 0 1

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

unname(model.matrix(~gl(3,4) + 0))

      [,1] [,2] [,3]
 [1,]    1    0    0
 [2,]    1    0    0
 [3,]    1    0    0
 [4,]    1    0    0
 [5,]    0    1    0
 [6,]    0    1    0
 [7,]    0    1    0
 [8,]    0    1    0
 [9,]    0    0    1
[10,]    0    0    1
[11,]    0    0    1
[12,]    0    0    1

Another Option:

as.matrix(Matrix::bdiag(rep(list(rep(1,4)),3)))

      [,1] [,2] [,3]
 [1,]    1    0    0
 [2,]    1    0    0
 [3,]    1    0    0
 [4,]    1    0    0
 [5,]    0    1    0
 [6,]    0    1    0
 [7,]    0    1    0
 [8,]    0    1    0
 [9,]    0    0    1
[10,]    0    0    1
[11,]    0    0    1
[12,]    0    0    1

as.matrix(Matrix::bdiag(replicate(3, numeric(4)+1, FALSE)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading