Let's say I have two matrices A and B with the same dimensions like follow:
A = matrix(1:30, nrow=3, ncol=10)
B = matrix(30:1, nrow=3, ncol=10)
#dim(A) = dim(B)
#[1] 3 10
A
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 4 7 10 13 16 19 22 25 28
[2,] 2 5 8 11 14 17 20 23 26 29
[3,] 3 6 9 12 15 18 21 24 27 30
B
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 30 27 24 21 18 15 12 9 6 3
[2,] 29 26 23 20 17 14 11 8 5 2
[3,] 28 25 22 19 16 13 10 7 4 1
Is there an R function to concatenate these two matrices column by column to get a single matrix as follows?
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
[1,] 1 30 4 27 7 24 10 21 13 18 16 15 19 12 22 9 25 6 28 3
[2,] 2 29 5 26 8 23 11 20 14 17 17 14 20 11 23 8 26 5 29 2
[3,] 3 28 6 25 9 22 12 19 15 16 18 13 21 10 24 7 27 4 30 1
here is my code, is there any way to optimize it?
C = matrix(NA, nrow=3, ncol=20)
j=1
for(i in 1:10){
C[,j] = A[,i]
C[,j+1] = B[,i]
j=j+2
}
Thank you
matrix(rbind(A,B), nrow=3)