我有一个对称矩阵,我想把它转换成R中的上三角/下三角矩阵。有没有办法做到这一点?
我无法使用upper.tri
和lower.tri
执行此操作。使用这些为我提供了一个矩阵,其条目为TRUE
或FALSE
。
答案 0 :(得分:28)
获得上三角矩阵:
mat <- matrix(1:9, 3, 3)
mat[lower.tri(mat)] <- 0
要删除对角线,请使用:
按照Karolis的评论建议 mat[lower.tri(mat,diag=TRUE)] <- 0
或mat[!upper.tri(mat)] <- 0
。
答案 1 :(得分:3)
虽然之前的答案很完美,但the manual是您的朋友:
矩阵的下三角部分和上三角部分
描述
返回与给定矩阵大小相同的逻辑矩阵 条目在下三角或上三角形中为TRUE。
用法
x
参数
diag
矩阵。
(m2 <- matrix(1:20, 4, 5)) lower.tri(m2) m2[lower.tri(m2)] <- NA m2
逻辑。是否应该包括对角线?
另请参阅
实施例
<LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1"> <TextView android:id="@+id/costOperatingText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Operating cost:" /> <TextView android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="0"/> </LinearLayout> <LinearLayout android:id="@+id/linearLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="6"> <TextView android:id="@+id/earnings" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Daily Earnings: " /> <TextView android:id="@+id/earningsValue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="0" /> </LinearLayout>
答案 2 :(得分:2)
一种简单的方法:
lower.triangle(X) #lower triangular
upper.triangle(X) #upper triangular
或者:
library(Matrix)
tril(X) #lower triangular
triu(X) #upper triangular