Home > Net >  r behaves strangely copying eigenvectors to a matrix in a for i loop
r behaves strangely copying eigenvectors to a matrix in a for i loop

Time:04-26

I'm a bit confused. A matrix A has 8 eigenvalues, some of them are complex, some are real. I want to copy only the eigenvectors that correspond to the real eigenvalues as columns into a Matrix M, otherwise the column should be filled with 0s. I use the code:

M <- matrix(,ncol=8,nrow=8)
for(i in 1:8) {
 M[,i] <- ifelse(Im(eigen(A)$val[i]) == 0, eigen(A)$vec[,i], 0)
}

but the result is as if I executed this one:

M <- matrix(,ncol=8,nrow=8)
for(i in 1:8) {
 M[,i] <- ifelse(Im(eigen(A)$val[i]) == 0, eigen(A)$vec[**1**,i], 0)
}

(that BTW in deed generates exactly the same output as the code above). Where is my misconception?

CodePudding user response:

I found the solution through the [email protected]: it's not a matter of matrix or for i loop behavior, it's a matter of ifelse that behaves in R very different to e.g ifelse in C. So the correct way to process my idea is:

for(i in 1:8) {
     M[,i] <- if(Im(eigen(A)$val[i]) == 0) eigen(A)$vec[,i] else 0
 }
  • Related