Created
November 11, 2019 14:18
-
-
Save bquast/4653082fd163e97b16e5ec4f1acd1cfb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# contructor function | |
tensor <- function(x) { | |
# check that it's numeric | |
if (!is.numeric(x)) stop("X must be numeric") | |
# create the array and change the class | |
y <- structure(array(x), class = "tensor") | |
# add attributes | |
attributes(y)$creators <- list() | |
attributes(y)$create_op <- list() | |
return(y) | |
} | |
a <- tensor(1:5) | |
# define a generic for sum | |
tensorsum <- function(x,y) UseMethod("tensorsum") | |
# define a sum method for tensor | |
tensorsum.tensor <- function(x,y) { | |
# calcluate the output | |
z <- x + y | |
# set attributes | |
attributes(z)$creators <- list(x = deparse(substitute(x)), y = deparse(substitute(y)) ) | |
attributes(z)$create_op <- "sum" | |
# return the output | |
return(z) | |
} | |
tensorsum(a, a) | |
# define a generic for sum | |
tensorprod <- function(x,y) UseMethod("tensorprod") | |
# define a sum method for tensor | |
tensorprod.tensor <- function(x,y) { | |
# calcluate the output | |
z <- x * y | |
# set attributes | |
attributes(z)$creators <- list(x = deparse(substitute(x)), y = deparse(substitute(y)) ) | |
attributes(z)$create_op <- "prod" | |
# return the output | |
return(z) | |
} | |
tensorprod(a,a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment