将R中的一个矩阵转换成一个上三角/下三角矩阵和相应的项。

时间:2022-01-16 13:05:44

I have a symmetric matrix and I want to convert it into a upper triangular/lower triangular matrix in R. Is there a way of doing this ?

我有一个对称矩阵,我想把它转换成r中的上三角/下三角矩阵,有办法吗?

I am not able to do this using upper.tri and lower.tri. Using these gives me a matrix with entries as either TRUE or FALSE.

我不能用上限。三,lower.tri。使用这些可以给我一个矩阵,其中的条目要么为真,要么为假。

3 个解决方案

#1


21  

To get the upper triangular matrix:

得到上三角矩阵:

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

To remove diagonal, use:

删除对角线,使用:

mat[lower.tri(mat,diag=TRUE)] <- 0 or mat[!upper.tri(mat)] <- 0 as suggested in the comments by Karolis.

style = ' font - size: 9.0 pt; font - family:宋体;mso - ascii - font - family: calibri; mso - ascii - theme - font:

#2


2  

While the previous answer is perfect, the manual is your friend:

虽然前面的答案是完美的,但手册是你的朋友:

Lower and Upper Triangular Part of a Matrix

Description

Returns a matrix of logicals the same size of a given matrix with entries TRUE in the lower or upper triangle.

返回一个逻辑矩阵,其大小与给定矩阵相同,且在下三角或上三角中条目为真。

Usage

lower.tri(x, diag = FALSE)
upper.tri(x, diag = FALSE)

Arguments

x     

a matrix.

一个矩阵。

diag

logical. Should the diagonal be included?

合乎逻辑的。对角线应该包括在内吗?

See Also

diag, matrix.

诊断接头,矩阵。

Examples

(m2 <- matrix(1:20, 4, 5))
lower.tri(m2)
m2[lower.tri(m2)] <- NA
m2

#3


1  

A simple way:

一个简单的方法:

lower.triangle(X) #lower triangular

lower.triangle(X)#下三角

upper.triangle(X) #upper triangular

upper.triangle(X)#上三角

Or:

或者:

library(Matrix)

库(矩阵)

tril(X) #lower triangular

下三角阵(X)#下三角

triu(X) #upper triangular

triu(X)#上三角

#1


21  

To get the upper triangular matrix:

得到上三角矩阵:

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

To remove diagonal, use:

删除对角线,使用:

mat[lower.tri(mat,diag=TRUE)] <- 0 or mat[!upper.tri(mat)] <- 0 as suggested in the comments by Karolis.

style = ' font - size: 9.0 pt; font - family:宋体;mso - ascii - font - family: calibri; mso - ascii - theme - font:

#2


2  

While the previous answer is perfect, the manual is your friend:

虽然前面的答案是完美的,但手册是你的朋友:

Lower and Upper Triangular Part of a Matrix

Description

Returns a matrix of logicals the same size of a given matrix with entries TRUE in the lower or upper triangle.

返回一个逻辑矩阵,其大小与给定矩阵相同,且在下三角或上三角中条目为真。

Usage

lower.tri(x, diag = FALSE)
upper.tri(x, diag = FALSE)

Arguments

x     

a matrix.

一个矩阵。

diag

logical. Should the diagonal be included?

合乎逻辑的。对角线应该包括在内吗?

See Also

diag, matrix.

诊断接头,矩阵。

Examples

(m2 <- matrix(1:20, 4, 5))
lower.tri(m2)
m2[lower.tri(m2)] <- NA
m2

#3


1  

A simple way:

一个简单的方法:

lower.triangle(X) #lower triangular

lower.triangle(X)#下三角

upper.triangle(X) #upper triangular

upper.triangle(X)#上三角

Or:

或者:

library(Matrix)

库(矩阵)

tril(X) #lower triangular

下三角阵(X)#下三角

triu(X) #upper triangular

triu(X)#上三角