Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining matrices by alternating columns

Tags:

r

matrix

I'm looking for a general approach to combine two matrices so that the columns from the two initial matrices alternate in the new matrix

col1m1...col1m2...col2m1...col2m2...col3m1...col3m2......

for example:

matrix.odd  <- matrix(c(rep(1,3),rep(3,3),rep(5,3)),nrow=3,ncol=3)
matrix.even <- matrix(c(rep(2,3),rep(4,3),rep(6,3)),nrow=3,ncol=3)
# would look like
matrix.combined <- matrix(c(rep(1,3),rep(2,3),rep(3,3),rep(4,3),rep(5,3),rep(6,3)),
                          nrow=3,ncol=6)

I'm looking for a general approach because I will have matrix combinations with more than just 3 columns. I've tried some for loops and some if statements but it isn't really coming together for me. Searches on combining matrices with shuffle and with alternation have not proven fruitful either. Any thoughts?

like image 811
Will Phillips Avatar asked Sep 17 '13 22:09

Will Phillips


2 Answers

Smth like this should do:

m <- cbind(matrix.odd, matrix.even)                   # combine
m <- m[, c(matrix(1:ncol(m), nrow = 2, byrow = T))]   # then reorder

Another option for fun:

matrix(rbind(matrix.odd, matrix.even), nrow = nrow(matrix.odd))

And to play the many matrices game:

weave = function(...) {
  l = list(...)
  matrix(do.call(rbind, l), nrow = nrow(l[[1]]))
}
like image 141
eddi Avatar answered Sep 19 '22 15:09

eddi


rows.combined <- nrow(matrix.odd) 
cols.combined <- ncol(matrix.odd) + ncol(matrix.even)
matrix.combined <- matrix(NA, nrow=rows.combined, ncol=cols.combined)
matrix.combined[, seq(1, cols.combined, 2)] <- matrix.odd
matrix.combined[, seq(2, cols.combined, 2)] <- matrix.even
like image 21
zero323 Avatar answered Sep 17 '22 15:09

zero323