symmatrix: Create a Symmetric Matrix from a Triangular Subset

View source: R/halfmatrix.R

symmatrixR Documentation

Create a Symmetric Matrix from a Triangular Subset

Description

Given a vector containing values for the upper or lower triangular entries of a matrix, reconstruct the original matrix, assuming it is symmetric.

Usage

symmatrix(x, from = c("lower", "upper"), diag = TRUE, na.value=NA)

Arguments

x

A vector or sparse vector of atomic values.

from

Character string (partially matched) specifying whether the entries of x represent the upper or lower triangular entries of the matrix.

diag

Logical value specifying whether x includes diagonal entries of the matrix.

na.value

Value to be assigned to diagonal entries of the matrix, if diag=FALSE.

Details

This function reconstructs a symmetric matrix from its lower triangular entries, or from its upper triangular entries.

  • If from="lower" (the default), the vector x is assumed to contain the lower-triangular entries of a matrix M (that is, the entries M[i,j] in row i and column j where i \ge j) listed in column-major order (that is, all of column 1 first, then all the relevant entries in column 2, etc.). This vector could have been obtained from the matrix by x <- M[lower.tri(M, diag)].

  • If from="upper", the vector x is assumed to contain the upper-triangular entries (those for which i \le j) listed in column-major order. This vector could have been obtained from the matrix by x <- M[upper.tri(M, diag)].

Assuming M was a symmetric matrix, it will be reconstructed from these values. The reconstructed matrix is returned.

If diag is FALSE, then the diagonal entries of the matrix are assumed to have been omitted, and the resulting matrix will contain NA entries in the diagonal.

If x is a sparse vector (inheriting class "sparseVector") the result is a sparse matrix (inheriting classes "sparseMatrix" and "symmetricMatrix").

Value

A symmetric, square matrix or sparse matrix, containing values of the same atomic type as x.

Author(s)

\adrian

.

See Also

lower.tri

Examples

  M <- matrix(c(10,  2, 3, 4,
                 2, 20, 5, 6,
                 3,  5, 30, 7,
                 4,  6, 7, 40), 4, 4)
  M

  (x <- M[lower.tri(M, diag=TRUE)])
  symmatrix(x)

  xsp <- as(x, "sparseVector")
  symmatrix(xsp)

  (y <- M[upper.tri(M, diag=FALSE)])
  symmatrix(y, from="upper", diag=FALSE)


spatstat.sparse documentation built on May 21, 2026, 9:07 a.m.