[英]A Matlab structure-like in R
我正在研究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類的想法之前,我想知道我是朝着正確的方向前進,還是有更好的選擇。
我想我發現重新創建此對象的最佳方法是使用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對象抽象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.