R: Conversion between Lower Triangular Matrix and Vector

This post shows how to convert a lower triangular matrix into a vector or vice versa using R code.



R code


The following R code efficiently converts between a lower triangular matrix and a vector, supporting both row-wise and column-wise operations for diverse purposes.

#-----------------------------------------------
# 1) Extract the lower triangular part (LTP)
#    of matrix as a vector
#-----------------------------------------------
mat <- matrix(1:9, nrow = 3)
 
# column-wise
v_cw <- mat[lower.tri(mat, diag = TRUE)] 
# row-wise
v_rw <- c(t(mat))[c(t(lower.tri(mat, diag = TRUE)))] 
 
cat("Input matrix:\n"); print(mat)
 
# vector containing the LTP
print(v_cw)
print(v_rw)
 
#-----------------------------------------------
# 2) Insert a vector into 
#    the lower triangular part of matrix
#-----------------------------------------------
<- B <- matrix(0,3,3)
 
# column-wise
A[lower.tri(A, diag = TRUE)] <- v_cw
# row-wise
B[t(lower.tri(B, diag = TRUE))] <- v_rw; B <- t(B)
 
# reconstructed lower triangular matrix 
print(A) 
print(B) 
 
cs


Output for the above code is as follows.

Input matrix:
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
> 
> # vector containing the LTP
> print(v_cw)
[11 2 3 5 6 9
> print(v_rw)
[11 2 5 3 6 9
> 
> 
> # reconstructed lower triangular matrix 
> print(A) 
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    2    5    0
[3,]    3    6    9
> print(B) 
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    2    5    0
[3,]    3    6    9
 
cs



No comments:

Post a Comment

Tentative Topics (Keeping Track to Avoid Forgetting)

Segmented Nelson-Siegel model
Shifting Endpoints Nelson-Siegel model
Nadaraya-Watson estimator
Locally weighted scatterplot smoothing (LOWESS)
Time-Varying Parameter Vector Autoregressions (TVP-VAR)
Time-varying or Dynamic Copula
Bayesian VAR
Adrian-Crump-Moench (ACM) term premium model
GARCH-EVT-Copula approach