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
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.
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 .
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.
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)
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With