qwertytam
qwertytam

Reputation: 167

Calculate each element in a matrix based on elements in two other matrices

I'm trying to populate a matrix with i x j entries from a random normal distribution based on the means and standard deviations stored in two other matrices. Is there a way to use rnorm pulling each entry from the two "data" matrices (the two matrices with the means and standard deviations) without using a loop?

Upvotes: 0

Views: 136

Answers (1)

user2554330
user2554330

Reputation: 44788

Sure, just do it:

means <- matrix(1:4, 2, 2)
sds <- matrix((1:4)/1000, 2, 2)
result <- matrix(rnorm(4, mean = means, sd = sds), 2, 2)

or (following the comment from Frank below)

result <- array(rnorm(length(means), mean = means, sd = sds),
                dim = dim(means)) 

Upvotes: 3

Related Questions