How to do R multiplication with Nx1 1xM for Matrix NxM?

后端 未结 3 1695
野性不改
野性不改 2020-12-20 09:28

I want to do a simple column (Nx1) times row (1xM) multiplication, resulting in (NxM) matrix. Code where I create a row by sequence, and column by transposing a similar seq

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-20 09:58

    An easy way to look at this is to transform your vectors to a matrix

    row1.mat = matrix(row1)
    col1.mat = matrix(col1)
    

    and then use dim to see the dimension of the matrices:

    dim(row1.mat)
    dim(col1.mat)
    

    If you want the product to work for this you need a 6*1 matrix, multiplied by a 1*6 matrix. so you need to transpose the col1.mat using t(col1.mat).

    And as you might know the matrix product is %*%

    row1.mat %*% t(col1.mat)
    

    Comparison of this method to others

    library("microbenchmark")
    x <- runif(1000)
    y <- runif(1000)
    xx = matrix(x)
    yy = matrix(y)
    microbenchmark(tcrossprod(x,y),x%*%t(y),outer(x,y), xx %*% t(yy), times=2000)
    
    Unit: milliseconds
                 expr      min       lq     mean   median       uq      max neval
     tcrossprod(x, y) 2.829099 3.243785 6.015880 4.801640 5.040636 77.87932  2000
           x %*% t(y) 2.847175 3.251414 5.942841 4.810261 5.049474 86.53374  2000
          outer(x, y) 2.886059 3.277811 5.983455 4.788054 5.074997 96.12442  2000
         xx %*% t(yy) 2.868185 3.255833 6.126183 4.699884 5.056234 87.80024  2000
    

提交回复
热议问题