is.symmetric.matrix: Is a matrix symmetric or positive-definite?

Description Usage Arguments Details Note Examples

View source: R/is_symmetric_matrix.R

Description

Determines if a matrix is square, symmetric, positive-definite, or positive-semi-definite.

Usage

1
2
3
4
5
6
7
is.square.matrix(A)

is.symmetric.matrix(A, tol = .Machine$double.eps^0.5)

is.positive.semi.definite(A, tol = .Machine$double.eps^0.5)

is.positive.definite(A, tol = .Machine$double.eps^0.5)

Arguments

A

A numeric matrix.

tol

A numeric tolerance level used to check if a matrix is symmetric. That is, a matrix is symmetric if the difference between the matrix and its transpose is between -tol and tol.

Details

A tolerance is added to indicate if a matrix A is approximately symmetric. If A is not symmetric, a message and first few rows of the matrix is printed. If A has any missing values, NA is returned.

Note

Functions are adapted from Frederick Novomestky's matrixcalc package in order to implement the rmatnorm function. The following changes are made:

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
## Example 0: Not square matrix
B <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, byrow = TRUE)
B
is.square.matrix(B)

## Example 1: Not a matrix. should get an error.
df <- as.data.frame(matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, byrow = TRUE))
df
## Not run: 
is.square.matrix(df)

## End(Not run)

## Example 2: Not symmetric & compare against matrixcalc
F <- matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE)
F
is.square.matrix(F)
is.symmetric.matrix(F) # should be FALSE
if (!requireNamespace("matrixcalc", quietly = TRUE)) {
  matrixcalc::is.symmetric.matrix(F)
} else {
  message("you need to install the package matrixcalc to compare this example")
}

## Example 3: Symmetric but negative-definite. The functions are same.
# eigenvalues are  3 -1
G <- matrix(c(1, 2, 2, 1), nrow = 2, byrow = TRUE)
G
is.symmetric.matrix(G)
if (!requireNamespace("matrixcalc", quietly = TRUE)) {
  matrixcalc::is.symmetric.matrix(G)
} else {
  message("you need to install the package matrixcalc to compare this example.")
}
isSymmetric.matrix(G)
is.positive.definite(G) # FALSE
is.positive.semi.definite(G) # FALSE

## Example 3b: A missing value in G
G[1, 1] <- NA
is.symmetric.matrix(G) # NA
is.positive.definite(G) # NA

## Example 4: positive definite matrix
# eigenvalues are 3.4142136 2.0000000 0.585786
Q <- matrix(c(2, -1, 0, -1, 2, -1, 0, -1, 2), nrow = 3, byrow = TRUE)
is.symmetric.matrix(Q)
is.positive.definite(Q)

## Example 5: identity matrix is always positive definite
I <- diag(1, 3)
is.square.matrix(I) # TRUE
is.symmetric.matrix(I) # TRUE
is.positive.definite(I) # TRUE

phargarten2/matrixNormal documentation built on Dec. 31, 2021, 12:06 a.m.