简体   繁体   中英

A Matlab structure-like in R

I am working on reservoir simulation objects in R and in a certain way I am trying to replicate a structure in Matlab that will work in 3D. The object has several attributes.

Grid.Nx, Grid.Ny, Grid.Nz,
Grid.hz, Grid.hy, Grid.hy,
Grid.por

This is Matlab/Octave works great. For instance, if I type Grid , it automatically will show all the attributes and values that Grid holds. The object in R that behaves closer I can think of is list(). But it not quite the same.

I came up with doing this using S4 classes, like this:

setClass("Grid", slots = c(
    Nx = "numeric",
    Ny = "numeric",
    Nz = "numeric",
    por = "numeric"
))

setGeneric("Grid.Nx<-", function(object, value){standardGeneric("Grid.Nx<-")})
setReplaceMethod(f="Grid.Nx", signature="Grid", 
                 definition=function(object, value){ 
                     object@Nx <- value
                     return (object)
})

setGeneric("Grid.Ny<-", function(object, value){standardGeneric("Grid.Ny<-")})
setReplaceMethod(f="Grid.Ny", signature="Grid", 
                 definition=function(object, value){ 
                     object@Ny <- value
                     return (object)
})

setGeneric("Grid.Nz<-", function(object, value){standardGeneric("Grid.Nz<-")})
setReplaceMethod(f="Grid.Nz", signature="Grid", 
                 definition=function(object, value){ 
                     object@Nz <- value
                     return (object)
})

Grid.Nx <- 3
Grid.Ny <- 8
Grid.Nz <- 4
Grid.Nx
Grid.Ny
Grid.Nz

There are few other objects in the simulation project that work like this. Before moving on with this idea of the S4 classes, I wanted to know if I moving in the right direction, or there are better alternatives.

I think I found that the best way of recreating this object is using R6 classes:

Grid <- R6Class("Grid",
    public = list(
        Nx = 0, Ny = 0, Nz = 0,
        hx = 0, hy = 0, hz = 0,
        K  = NA,
        N  = NA,
    initialize = function(Nx, Ny, Nz) { 
        self$Nx = Nx
        self$Ny = Ny
        self$Nz = Nz
        self$hx = 1 / self$Nx
        self$hy = 1 / self$Ny
        self$hz = 1 / self$Nz
        self$K  = array(1, c(3, self$Nx, self$Ny))
        self$N  = self$Nx * self$Ny * self$Nz
        cat(sprintf("Grid of %dx%dx%d", self$Nx, self$Ny, self$Nz))
        image(self$K[1,,])
        }
    )
)

grid <- Grid$new(8, 8, 1)
# Grid of 8x8x1

It is less verbose than S4 and kind of follows -not 100% exactly- the Matlab object abstraction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM