I need to solve a system of linear equations:
aQ + bP = c
dQ + eP = f
Where:
a ~ N(100;10)
b ~ N(-1;0.1)
c ~ N(10;1)
d ~ N(10;0.1)
e ~ N(100;10)
f ~ N(10;0.1)
So far I have written:
a <- rnorm(100, mean=100, sd=10)
b <- rnorm(100, mean=-1, sd=0.1)
c <- rnorm(100, mean=10, sd=1)
d <- rnorm(100, mean=10, sd=0.1)
e <- rnorm(100, mean=100, sd=10)
f <- rnorm(100, mean=10, sd=0.1)
P <- vector()
Q <- vector()
for (i in 1:100) {
coefs <- matrix(c(a[i],d[i],b[i],e[i]),2,2)
ys <- array(c(c,f),2)
solve(coefs[i], ys[i])
}
The problem is that the for loop is only giving me one solution for P and Q and I would like that the for loop to calculate the 100 set of values do a,b,c,d,e and f and store the data on the vectors Q and P.
Just to offer another possible approach, you could use
mapply()
to effectively iterate over each coefficient and RHS vector in parallel:Or if you prefer getting the results as a list, you could pass
SIMPLIFY=F
tomapply()
, or just useMap()
, which doesn't simplify by default:You could try using
apply()
Or else using
sapply()
and if you want to use
for
loop, here is what you could do