Janak
Janak

Reputation: 683

r: how to make matrix multiplication faster (special case)

I want to have a matrix d3 (m x n) whose each row is identical and equal to a given vector (d0) with dimension n.

My try was the following: Let

 m=1000
 n=20000
 d0=runif(n)
 d1=diag(d0)
 d2=array(1,dim=c(m,n)).

I would like to compute the product of the above two matrix, d3, where

 d3=d2%*%d1.

This straightforward way of matrix multiplication is very slow. How to make multiplication faster in the above special case? Thanks.

Upvotes: 0

Views: 463

Answers (1)

Roland
Roland

Reputation: 132706

I want to have a matrix d3 (m x n) whose each row is identical and equal to a given vector (d0) with dimension n.

This is trivial to do using the matrix function and vector recycling.

m=4
n=5
set.seed(42)
d0=runif(n)
matrix(d0, nrow = m, ncol = n, byrow = TRUE)
#         [,1]      [,2]      [,3]      [,4]      [,5]
#[1,] 0.914806 0.9370754 0.2861395 0.8304476 0.6417455
#[2,] 0.914806 0.9370754 0.2861395 0.8304476 0.6417455
#[3,] 0.914806 0.9370754 0.2861395 0.8304476 0.6417455
#[4,] 0.914806 0.9370754 0.2861395 0.8304476 0.6417455

This should be the fastest solution.

Upvotes: 2

Related Questions