Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a matrix using recycling

Tags:

r

matrix

recycle

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.

like image 602
james black Avatar asked Mar 28 '26 19:03

james black


2 Answers

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
like image 175
Count Orlok Avatar answered Mar 31 '26 10:03

Count Orlok


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)
like image 20
Henrik Avatar answered Mar 31 '26 08:03

Henrik



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!