简体   繁体   中英

R: extract parts of matrices in loops - loop only run once

I am not an advanced user, but I have been trying to solve this problem for many hours now and I do not know how else to proceed.

SETTING: I have a 2X10000 matrix, which is constituted of 10000 repetitions of 2 variables, call them a and b,in row 1 and 2 respectively. I need an operation repeated for every column (ie 10000 times), hence the loop. The operation is the following: for every column [ab]', create a 2x2 matrix looking like this:

[a  b]
[b  a]

then transpose this matrix and multiply it by the original column column. At the end I should obtain, for each original column [ab]', another column but with two different values.

I build the 2x10000 matrix to contain the result:

R <- 10000
a <- matrix(rep(1, 200), nrow=2, ncol=R)

Gamma is the 2x10000 matrix whose columns I am using. Then I apply the following loop:

for (j in 1:R) {
  Big_Gamma = matrix(c(Gamma[1, j], Gamma[2, j], Gamma[2, j], Gamma[1, j]), nrow=2, ncol=2);
  a <- solve(Big_Gamma)%*%Gamma[, j];
}

Big_Gamma is the 2x2 matrix I need to invert and multiply by the original vector. Again, I need this done for each of the 10000 vectors and I need another vector (of equal dimension as the original one) as output (if possible). I tried different specifications, also in the way I extract the columns, but it always only runs once (ie the matrix a changes and becomes a 2x1 one)

I have looked for hours on various sites and could not find an answer. I hope the question is not too stupid. Thank you in advance, soo much!

You are overwriting a on each iteration. Try:

R <- 10000
a <- matrix(rep(1, 200), nrow=2, ncol=R)
for (j in 1:R) {
  Big_Gamma = matrix(c(Gamma[1, j], Gamma[2, j], Gamma[2, j], Gamma[1, j]), nrow=2, ncol=2);
  a[, j] <- solve(Big_Gamma)%*%Gamma[, j];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM