R/sqrt.mat.R

Defines functions sqrt_mat

Documented in sqrt_mat

#' sqrt_mat
#' 
#' sqrt_mat performs the square root of a matrix only for square symmetric matrices
#' This function should not be used directly.
#' 
#' @param X a matrix that is square and symmetric
#' 
#' @author Derek Beaton
#' @export sqrt_mat

##a function specifically for sqrt'ing a matrix for the GSVD weights.
sqrt_mat <- function(X){
  
  ##first, test if it is symmetric in size
  if(!isSymmetric.matrix(X)){
    stop("Weight/Mass matrix is not symmetric")
  }
  ##test if it is a diagonal matrix -- then just sqrt it and send back.
  if(isDiagonal.matrix(X)){
    return(  sqrt(diag(X)) ) ##return the vector so we can be fast about it.
  }else{
    A <- eigen(X)
    ##change values below tolerance
    A$values[which(A$values < .Machine$double.eps)] <- 0
    ##first, test if positive definite
    if( sum(A$values < 0 )>0 ){
      stop("Weight/Mass matrix not positive definite. Some eigenvalues are less than 0")	
    }else{		
      return(A$vectors %*% diag(sqrt(A$values)) %*% t(A$vectors))
    }
  }
}

Try the ExPosition package in your browser

Any scripts or data that you put into this service are public.

ExPosition documentation built on April 13, 2025, 5:08 p.m.