将R中的矩阵转换为具有相应条目的上三角/下三角矩阵

时间:2014-10-15 07:49:06

标签: r matrix

我有一个对称矩阵,我想把它转换成R中的上三角/下三角矩阵。有没有办法做到这一点?

我无法使用upper.trilower.tri执行此操作。使用这些为我提供了一个矩阵,其条目为TRUEFALSE

3 个答案:

答案 0 :(得分:28)

获得上三角矩阵:

mat <- matrix(1:9, 3, 3)
mat[lower.tri(mat)] <- 0

要删除对角线,请使用:

按照Karolis的评论建议

mat[lower.tri(mat,diag=TRUE)] <- 0mat[!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
     

逻辑。是否应该包括对角线?

     

另请参阅

     

diagmatrix

     

实施例

<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