Reputation: 185
I have a very simple question here. I have been trying to save my results from the loop as a vector. Below is my reproducible code:-
a = matrix( c(0.7, 0.3, 0.2, 0.8),nrow=2, ncol=2, byrow = TRUE)
b = matrix( c(0.02, 0.45, 0.15, 0.30),nrow=2, ncol=2, byrow = TRUE)
d = 0
myvector <- c()
for (i in 1:2) {
d = d + (a[, i] * b[, i])
myvector[i] <- d
}
myvector
[1] 0.014 0.149
Why it did not give me the whole vector? It only give me the answer for the first row. How do we store the result from the loop as vector?
Upvotes: 0
Views: 145
Reputation: 1553
Try this:
a = matrix( c(0.7, 0.3, 0.2, 0.8),nrow=2, ncol=2, byrow = TRUE)
b = matrix( c(0.02, 0.45, 0.15, 0.30),nrow=2, ncol=2, byrow = TRUE)
d = 0
myvector <- vector()
for (i in 1:2){
d = d + (a[,i] * b[,i])
myvector <- c(myvector, d)
}
Upvotes: 1