r的行为奇怪地将特征向量复制到i循环中的矩阵

发布于 2025-01-23 05:32:11 字数 431 浏览 3 评论 0原文

我有点困惑。一个矩阵A具有8个特征值,其中有些是复杂的,有些是真实的。我想仅将与真实特征值相对应的特征向量复制为矩阵M,否则应用0填充列。我使用该代码:

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)
}

但是结果好像我执行了此:(

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)
}

契约中的BTW生成的输出与上面的代码完全相同)。我的误解在哪里?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只有一腔孤勇 2025-01-30 05:32:11

我通过

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

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
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文