Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert upper triangular part of a matrix to 3-column long format

Tags:

r

matrix

I want Convert matrix to three defined columns in R. This is an example:

input

     col1  col2  col3
row1  1     2     3 
row2  2     3     4
row3  3     4     5

output:

row1 clo1 1
row1 col2 2
row1 col3 3
row2 col2 3
row2 col3 4
row3 col3 5
like image 224
Agrii Enginee Avatar asked Jan 19 '17 14:01

Agrii Enginee


People also ask

How do you invert a upper triangular matrix?

A standard algorithm to invert a matrix is to find its LU decomposition (decomposition into a lower-triangular and an upper-triangular matrix), use back subsitution on the triangular pieces, and then combine the results to obtain the inverse of the original matrix.

How do you extract upper triangular matrix in Matlab?

U = triu( A ) returns the upper triangular portion of matrix A . U = triu( A , k ) returns the elements on and above the kth diagonal of A .

What is the formula for upper triangular matrix?

If U is an n × n upper-triangular matrix, we know how to solve the linear system Ux = b using back substitution. In fact, this is the final step in the Gaussian elimination algorithm that we discussed in Chapter 2. Compute the value of xn = bn/unn, and then insert this value into equation (n − 1) to solve for xn−1.

What is upper triangular matrix 3x3?

The upper triangular matrix has all the elements below the main diagonal as zero. Also, the matrix which has elements above the main diagonal as zero is called a lower triangular matrix. Upper Triangular Matrix (U)


1 Answers

Suppose X is your matrix, we can do:

ind <- which(upper.tri(X, diag = TRUE), arr.ind = TRUE)
cbind(ind, X[ind])

In some cases you may want to use dim names. In that case, we have to arrange the result in a data frame, as the first two columns are character, while the third column is numeric.

ind <- which(upper.tri(X, diag = TRUE), arr.ind = TRUE)
nn <- dimnames(X)
data.frame(row = nn[[1]][ind[, 1]],
           col = nn[[2]][ind[, 2]],
           val = X[ind])
like image 87
Zheyuan Li Avatar answered Sep 27 '22 20:09

Zheyuan Li