From aaa4b9302c70abc094331a7b2a0d93786c3b9542 Mon Sep 17 00:00:00 2001 From: Waldir Leoncio Date: Wed, 15 Jan 2020 10:55:50 +0100 Subject: [PATCH] Fixed repmat --- R/repmat.R | 16 +++++++++++++--- man/repmat.Rd | 2 ++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/R/repmat.R b/R/repmat.R index fcc041f..be72325 100644 --- a/R/repmat.R +++ b/R/repmat.R @@ -6,13 +6,23 @@ #' @param n either a scalar with the number of replications in both rows and columns or a 2-length vector with individual repetitions. #' @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. +#' +#' 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. #' @export repmat <- function (mx, n) { + # Validation if (length(n) > 2) warning("Extra dimensions of n ignored") if (length(n) == 1) n <- rep(n, 2) - out <- mx_cols <- rep(mx, n[1]) - if (n[2] > 1) { - for (i in seq(n[2] - 1)) out <- rbind(out, mx_cols) + if (class(mx) != "matrix") mx <- as.matrix(mx) + + # 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) } + + # Output return(unname(as.matrix(out))) } \ No newline at end of file diff --git a/man/repmat.Rd b/man/repmat.Rd index f05885b..3ec7750 100644 --- a/man/repmat.Rd +++ b/man/repmat.Rd @@ -23,4 +23,6 @@ function on Matlab } \note{ The Matlab implementation of this function accepts `n` with length > 2. + +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. }