Force a Matrix to 'symmetricMatrix' Without Symmetry Checks
forceSymmetric-methods.RdForce a square matrix x to a symmetricMatrix,
without a symmetry check as it would be applied for as(x,
"symmetricMatrix").
Arguments
- x
any square matrix (of numbers), either “"traditional"” (
matrix) or inheriting fromMatrix.- uplo
optional string,
"U"or"L"indicating which “triangle” half ofxshould determine the result. The default is"U"unlessxalready has auploslot (i.e., when it issymmetricMatrix, ortriangularMatrix), where the default will bex@uplo.
Value
a square matrix inheriting from class
symmetricMatrix.
See also
symmpart for the symmetric part of a matrix, or
the coercions as(x, <symmetricMatrix class>).
Examples
## Hilbert matrix
i <- 1:6
h6 <- 1/outer(i - 1L, i, "+")
sd <- sqrt(diag(h6))
hh <- t(h6/sd)/sd # theoretically symmetric
isSymmetric(hh, tol=0) # FALSE; hence
#> [1] FALSE
try( as(hh, "symmetricMatrix") ) # fails, but this works fine:
#> 6 x 6 Matrix of class "dsyMatrix"
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 1.0000000 0.8660254 0.7453560 0.6614378 0.6000000 0.5527708
#> [2,] 0.8660254 1.0000000 0.9682458 0.9165151 0.8660254 0.8206518
#> [3,] 0.7453560 0.9682458 1.0000000 0.9860133 0.9583148 0.9270248
#> [4,] 0.6614378 0.9165151 0.9860133 1.0000000 0.9921567 0.9749960
#> [5,] 0.6000000 0.8660254 0.9583148 0.9921567 1.0000000 0.9949874
#> [6,] 0.5527708 0.8206518 0.9270248 0.9749960 0.9949874 1.0000000
H6 <- forceSymmetric(hh)
## result can be pretty surprising:
(M <- Matrix(1:36, 6))
#> 6 x 6 Matrix of class "dgeMatrix"
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 1 7 13 19 25 31
#> [2,] 2 8 14 20 26 32
#> [3,] 3 9 15 21 27 33
#> [4,] 4 10 16 22 28 34
#> [5,] 5 11 17 23 29 35
#> [6,] 6 12 18 24 30 36
forceSymmetric(M) # symmetric, hence very different in lower triangle
#> 6 x 6 Matrix of class "dsyMatrix"
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 1 7 13 19 25 31
#> [2,] 7 8 14 20 26 32
#> [3,] 13 14 15 21 27 33
#> [4,] 19 20 21 22 28 34
#> [5,] 25 26 27 28 29 35
#> [6,] 31 32 33 34 35 36
(tm <- tril(M))
#> 6 x 6 Matrix of class "dtrMatrix"
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 1 . . . . .
#> [2,] 2 8 . . . .
#> [3,] 3 9 15 . . .
#> [4,] 4 10 16 22 . .
#> [5,] 5 11 17 23 29 .
#> [6,] 6 12 18 24 30 36
forceSymmetric(tm)
#> 6 x 6 Matrix of class "dsyMatrix"
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 1 2 3 4 5 6
#> [2,] 2 8 9 10 11 12
#> [3,] 3 9 15 16 17 18
#> [4,] 4 10 16 22 23 24
#> [5,] 5 11 17 23 29 30
#> [6,] 6 12 18 24 30 36