https://github.com/cran/pracma
Raw File
Tip revision: e2512490ec9e26c0bfb230f9fd97bcf07cc8c07b authored by Hans W. Borchers on 10 November 2023, 00:10:02 UTC
version 2.4.4
Tip revision: e251249
size.R
##
##  s i z e . R  Matlab size, numel, ndims, and isempty functions
##


size <- function(x, k) {
	if (length(x) == 0)    sz <- 0
	else if (is.vector(x)) sz <- c(1, length(x))
	else if (is.array(x))  sz <- dim(x)
	else                   sz <- NULL

	if (!missing(k)) {
		if (k > length(sz)) sz <- 1
		else if (k >= 1)    sz <- sz[k]
		else
			stop("Requested dimension 'k' is out of range.")
	}
	return(sz)
}

numel <- function(x) {
	sz <- size(x)
	if (!is.null(sz)) prod(sz)
	else              return(NULL)
}

nnz <- function(x) {
    if (length(x) == 0) return(0)
    stopifnot(is.numeric(x) || is.complex(x))
    sum(x != 0)
}

ndims <- function(x) {
    if (length(x) == 0) nd <- 0
    else if (is.vector(x)) nd <- 1
    else if (is.array(x)) nd <- length(dim(x))
    else nd <- NA
    
    return(nd)
}

# ndims <- function(x) {
#   sz <- size(x)
#   if (!is.null(sz)) length(sz)
#   else              return(NULL)
# }

isempty <- function(x) {
	length(x) == 0
}
back to top