2019-12-17 10:53:59 +01:00
#' @title Repeat matrix
#' @description Repeats a matrix over n columns and rows
#' @details This function was created to replicate the behavior of a homonymous
#' function on Matlab
#' @param mx matrix
2020-02-25 14:28:54 +01:00
#' @param n either a scalar with the number of replications in both rows and
#' columns or a <= 3-length vector with individual repetitions.
2019-12-17 10:53:59 +01:00
#' @return matrix replicated over `ncol(mx) * n` columns and `nrow(mx) * n` rows
#' @note The Matlab implementation of this function accepts `n` with length > 2.
2020-02-25 14:28:54 +01:00
#'
2020-01-15 10:55:50 +01:00
#' It should also be noted that a concatenated vector in R, e.g. `c(5, 2)`, becomes a column vector when coerced to matrix, even though it may look like a row vector at first glance. This is important to keep in mind when considering the expected output of this function. Vectors in R make sense to be seen as column vectors, given R's Statistics-oriented paradigm where variables are usually disposed as columns in a dataset.
2019-12-17 10:53:59 +01:00
#' @export
repmat <- function ( mx , n ) {
2020-01-15 10:55:50 +01:00
# Validation
2020-02-25 14:28:54 +01:00
if ( length ( n ) > 3 ) warning ( " Extra dimensions of n ignored" )
2020-07-14 11:17:25 +02:00
if ( ! is ( mx , " matrix" ) ) mx <- t ( as.matrix ( mx ) )
2019-12-17 10:53:59 +01:00
if ( length ( n ) == 1 ) n <- rep ( n , 2 )
2021-02-15 09:03:44 +01:00
if ( any ( n == 0 ) ) {
n_zero <- which ( n == 0 )
out_dim <- dim ( mx )
out_dim [n_zero ] <- 0
return ( array ( dim = out_dim ) )
}
2020-01-15 10:55:50 +01:00
# Replicating cols
out <- mx_col <- matrix ( rep ( mx , n [2 ] ) , nrow ( mx ) )
# Replicating rows
if ( n [1 ] > 1 ) {
for ( i in seq ( n [1 ] - 1 ) ) out <- rbind ( out , mx_col )
2019-12-17 10:53:59 +01:00
}
2020-01-15 10:55:50 +01:00
2020-02-25 14:28:54 +01:00
# Replicating 3rd dimension
if ( ! is.na ( n [3 ] ) & n [3 ] > 1 ) out <- array ( out , c ( dim ( out ) , n [3 ] ) )
2020-01-15 10:55:50 +01:00
# Output
2020-02-25 14:28:54 +01:00
return ( unname ( as.array ( out ) ) )
2019-12-17 10:53:59 +01:00
}