Reputation: 357
If I sample
a<-rgamma(100, 4, 10)
b<-rnorm(100, 2, 6)
I want to sample a data matrix M
and each entry M(i,j)~Normal(a[i], b[j]
. For example,
M(1,1)<-rnorm(1, a[1], b[1])
But I do not know how to form this matrix? Like use for loop?
Upvotes: 0
Views: 277
Reputation: 17715
Here's an example with a 5x5 matrix. You can change the first line to make your matrix bigger.
Note that I inverted the order of a
and b
because it is impossible to draw from a normal distribution with negative standard deviation, and the b
vector includes negative values.
N <- 5
a <- rgamma(N, 4, 10)
b <- rnorm(N, 2, 6)
M <- matrix(ncol=N, nrow=N)
for (i in 1:N) {
for (j in 1:N) {
M[i, j] <- rnorm(1, mean=b[j], sd=sqrt(a[i]))
}
}
M
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 4.525953 14.10435 11.83800 1.922218 -3.360052
#> [2,] 4.504492 14.01858 11.62823 2.056981 -3.023448
#> [3,] 4.591491 14.23959 12.06540 2.054371 -3.187501
#> [4,] 3.819474 14.16737 11.63790 2.252287 -3.411978
#> [5,] 4.900445 13.72671 12.13339 2.494865 -3.264389
Upvotes: 1