R

时间:2017-07-24 05:55:47

标签: r matlab octave

我正在研究 R 中的油藏模拟对象,并且在某种程度上我试图在Matlab中复制一个可以在3D中工作的结构。该对象有几个属性。

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

这是Matlab / Octave的很好用。例如,如果我键入Grid,它会自动显示Grid所拥有的所有属性和值。我能想到的R中的对象是list()。但它并不完全相同。

我想到了这样做,使用S4类,如下:

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

模拟项目中很少有其他对象可以像这样工作。 在继续讨论 S4 课程的想法之前,我想知道我是否朝着正确的方向前进,或者有更好的选择。

1 个答案:

答案 0 :(得分:0)

我想我发现重新创建这个对象的最好方法是使用R6类:

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

它比S4更简洁,并且遵循以下 - 不完全是100% - Matlab对象抽象。