I am asked as an exercise to use recycling to initiate a 4 by 5 matrix where the first three rows are 0's and the fourth row has 4, 8, 12, 16, 20.
I understand that recycling is defined as if the lengths of the two vectors in a mathematical operation do not match, then the shorter vector is repeated until its length matches that of the larger vector. I have tried to create a matrix through the following and other things along the same line.
x = matrix(0,nrow=4,ncol=5) + c(4,8,12,16,20)
Of course this isn't correct so I am wondering what I am missing here. Any help is appreciated.
When called on vector arguments, rbind returns a matrix and recycles the vectors that are too short, making for a simple and elegant solution:
rbind(0, 0, 0, c(4, 8, 12, 16, 20))
# [,1] [,2] [,3] [,4] [,5]
# [1,] 0 0 0 0 0
# [2,] 0 0 0 0 0
# [3,] 0 0 0 0 0
# [4,] 4 8 12 16 20
Using modulo (%%):
matrix(1:20 * (1:20 %% 4 == 0), nrow = 4)
Written a bit more general:
nr = 4
nc = 5
v = seq(nr * nc)
matrix(v * (v %% nr == 0), nrow = nr)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With