2022-12-23 13:11:55 +01:00
|
|
|
ind2subv <- function(siz, ndx) {
|
|
|
|
|
# IND2SUBV Like the built - in ind2sub, but returns the answer as a row vector.
|
|
|
|
|
# sub <- ind2subv(siz, ndx)
|
|
|
|
|
# siz and ndx can be row or column vectors.
|
|
|
|
|
# sub will be of size length(ndx) * length(siz).
|
|
|
|
|
# Example
|
|
|
|
|
# ind2subv([2 2 2], 1:8) returns
|
|
|
|
|
# [1 1 1
|
|
|
|
|
# 2 1 1
|
|
|
|
|
# ...
|
|
|
|
|
# 2 2 2]
|
|
|
|
|
# That is, the leftmost digit toggle fastest.
|
|
|
|
|
#
|
|
|
|
|
# See also SUBV2IND
|
2022-12-22 15:04:44 +01:00
|
|
|
|
2022-12-23 13:11:55 +01:00
|
|
|
n <- length(siz)
|
2022-12-22 15:04:44 +01:00
|
|
|
|
2022-12-23 13:11:55 +01:00
|
|
|
if (n == 0) {
|
|
|
|
|
sub <- ndx
|
|
|
|
|
return(sub)
|
|
|
|
|
}
|
2022-12-22 15:04:44 +01:00
|
|
|
|
2022-12-23 13:11:55 +01:00
|
|
|
if (all(siz == 2)) {
|
2023-02-16 15:30:15 +01:00
|
|
|
sub <- t(vapply(ndx, function(x) dec2bitv(x - 1, n), c(0, 0, 0)))
|
2022-12-23 13:11:55 +01:00
|
|
|
sub <- sub[, seq(n, 1, - 1)] + 1
|
|
|
|
|
return(sub)
|
|
|
|
|
}
|
2022-12-22 15:04:44 +01:00
|
|
|
|
2022-12-23 13:11:55 +01:00
|
|
|
cp <- c(1, cumprod(t(siz[])))
|
|
|
|
|
ndx <- ndx[] - 1
|
|
|
|
|
sub <- zeros(length(ndx), n)
|
|
|
|
|
for (i in seq(n, 1, -1)) {# i'th digit
|
|
|
|
|
sub[, i] <- floor(ndx / cp[i]) + 1
|
2023-02-16 15:30:15 +01:00
|
|
|
ndx <- ndx %% cp[i]
|
2022-12-23 13:11:55 +01:00
|
|
|
}
|
|
|
|
|
return(sub)
|
|
|
|
|
}
|