tensor_predictors/tensorPredictors/R/matricize.R

24 lines
559 B
R

#' Matricization
#'
#' @param T multi-dimensional array of order at least \code{mode}
#' @param mode dimension along to matricize
#'
#' @returns matrix of dimensions \code{dim(T)[mode]} by \code{prod(dim(T))[-mode]}
#'
#' @export
mat <- function(T, mode) {
mode <- as.integer(mode)
dims <- dim(T)
if (length(dims) < mode) {
stop("Mode must be a pos. int. smaller equal than the tensor order")
}
if (mode > 1L) {
T <- aperm(T, c(mode, seq_along(dims)[-mode]))
}
dim(T) <- c(dims[mode], prod(dims[-mode]))
T
}