Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

matrix

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

like image 808
Vons Avatar asked Oct 15 '25 02:10

Vons


1 Answers

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)))
like image 83
KU99 Avatar answered Oct 17 '25 17:10

KU99



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!