Skip to navigation

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

6 Responses to “R: Combine two matrices column by column”

  1. Daniel Goldstein Says:

    Cool! How does that work?

  2. Marianne Says:

    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:

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

    where t(matrix(c(t(a),t(b)),3)) does what rbind(a,b) does.

  3. Habib Jafari Says:

    Hello

    I need to learn about :
    the combine of two matrices.

    thanke you very much
    Jafari

  4. Marianne Says:

    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:

    > a+b
         [,1] [,2] [,3]
    [1,]    5    7    9
    [2,]    5    7    9
    [3,]    5    7    9
    [4,]    5    7    9
    > c(a,b)
     [1] 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6
    > matrix(c(a,b),4)
         [,1] [,2] [,3] [,4] [,5] [,6]
    [1,]    1    2    3    4    5    6
    [2,]    1    2    3    4    5    6
    [3,]    1    2    3    4    5    6
    [4,]    1    2    3    4    5    6
    > cbind(a,b)
         [,1] [,2] [,3] [,4] [,5] [,6]
    [1,]    1    2    3    4    5    6
    [2,]    1    2    3    4    5    6
    [3,]    1    2    3    4    5    6
    [4,]    1    2    3    4    5    6
    > rbind(a,b)
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    1    2    3
    [3,]    1    2    3
    [4,]    1    2    3
    [5,]    4    5    6
    [6,]    4    5    6
    [7,]    4    5    6
    [8,]    4    5    6
    
  5. Nikos Alexandris Says:

    Very useful. Thank you ;-)

  6. Oscar Says:

    Thanks for your awesome answers!