Implemented base MATLAB function in R

This commit is contained in:
Waldir Leoncio 2020-01-30 15:44:13 +01:00
parent 309519dd08
commit e645d00fca
3 changed files with 72 additions and 0 deletions

30
R/size.R Normal file
View file

@ -0,0 +1,30 @@
#' @title Size of an object
#' @description This functions tries to replicate the behavior of the base function "size" in Matlab
#' @param x object to be evaluated
#' @param d dimension of object to be evaluated
#' @note On MATLAB, size(1, 100) returns 1. As a matter of fact, if the user
#' calls for a dimension which x doesn't have `size()` always returns 1. R's
#' default behavior is more reasonable in those cases (i.e., returning NA),
#' but since the point of this function is to replicate MATLAB behaviors
#' (bugs and questionable behaviors included), this function also does this.
size <- function(x, d) {
# Determining the number of dimensions
if (length(x) == 1) {
# x is surely a scalar
return(1)
} else {
# x is a vector, a matrix or an array
n_dim <- ifelse(is.null(dim(x)), 1, length(dim(x)))
if (missing(d)) {
if (n_dim == 1) {
out <- range(x)
} else {
out <- dim(x)
}
} else {
out <- ifelse(n_dim == 1, range(x)[d], dim(x)[d])
if (is.na(out)) out <- 1 # for MATLAB compatibility
}
return(out)
}
}

23
man/size.Rd Normal file
View file

@ -0,0 +1,23 @@
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/size.R
\name{size}
\alias{size}
\title{Size of an object}
\usage{
size(x, d)
}
\arguments{
\item{x}{object to be evaluated}
\item{d}{dimension of object to be evaluated}
}
\description{
This functions tries to replicate the behavior of the base function "size" in Matlab
}
\note{
On MATLAB, size(1, 100) returns 1. As a matter of fact, if the user
calls for a dimension which x doesn't have `size()` always returns 1. R's
default behavior is more reasonable in those cases (i.e., returning NA),
but since the point of this function is to replicate MATLAB behaviors
(bugs and questionable behaviors included), this function also does this.
}

View file

@ -65,4 +65,23 @@ test_that("times works as expected", {
test_that("colon works as expected (hee hee)", {
expect_equal(colon(1, 4), 1:4)
expect_length(colon(4, 1), 0)
})
test_that("size works as on MATLAB", {
sk <- 10
vk <- 1:4
mx <- matrix(1:6, 2)
ra <- array(1:24, c(2, 3, 4))
expect_equal(size(sk), 1)
expect_equal(size(vk), c(1, 4))
expect_equal(size(mx), c(2, 3))
expect_equal(size(ra), c(2, 3, 4))
expect_equal(size(sk, 199), 1)
expect_equal(size(vk, 199), 1)
expect_equal(size(mx, 199), 1)
expect_equal(size(ra, 199), 1)
expect_equal(size(vk, 2), 4)
expect_equal(size(mx, 2), 3)
expect_equal(size(ra, 2), 3)
expect_equal(size(ra, 3), 4)
})