## R: Combine two matrices column by column

I have two matrices. I want to combine these, alternatingly picking the next column from a and from b.

> a <- matrix(c(rep(c(1:3),each=4)),4) > a [,1] [,2] [,3] [1,] 1 2 3 [2,] 1 2 3 [3,] 1 2 3 [4,] 1 2 3 > b <- matrix(c(rep(c(4:6),each=4)),4) > b [,1] [,2] [,3] [1,] 4 5 6 [2,] 4 5 6 [3,] 4 5 6 [4,] 4 5 6 > matrix(rbind(a,b),4) [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 4 2 5 3 6 [2,] 1 4 2 5 3 6 [3,] 1 4 2 5 3 6 [4,] 1 4 2 5 3 6

July 12th, 2007 at 10:33

Cool! How does that work?

July 12th, 2007 at 11:11

Hi Dan!

I’m surprised someone is actually reading this blog :)

`rbind`

combines a and b row by row. Then`matrix`

goes column by column through the old`rbind(a,b)`

matrix to pick the values that form the new matrix with just four rows.Before I found

`rbind`

, I had this unwieldy solution:where

`t(matrix(c(t(a),t(b)),3))`

does what`rbind(a,b)`

does.September 19th, 2007 at 09:10

Hello

I need to learn about :

the combine of two matrices.

thanke you very much

Jafari

September 28th, 2007 at 10:37

Hi Habib,

You’d need to be a bit more specific.

In general, just try out different things to see what they do. Here are some examples:

April 27th, 2010 at 16:56

Very useful. Thank you ;-)

September 26th, 2012 at 23:16

Thanks for your awesome answers!