[英]Vectorizing a (recursive) function F#
F#的新手,因為我的主要工具是R,所以我發現這些“較低級別”的語言有點挑戰。 我正在嘗試編寫一個遞歸函數(Cox-de Boor),該函數給定輸入向量x(數組或類似值)將返回相同長度的向量。 其他參數是int,int和float []。 到目前為止,我只設法做到了一個x。 我很確定自己的代碼是愚蠢的,因此任何提示將不勝感激。
let rec basis (x:float) degree i (knots:float[]) =
let B=
match degree=0 with
|true -> if (x>=knots.[i-1] && x < knots.[i]) then 1.0 else 0.0
|false -> let Alpha1 =
match ((knots.[degree+i-1] - knots.[i-1])=0.0) with
|true -> 0.0
|false -> (x-knots.[i-1])/(knots.[degree+i-1]-knots.[i-1])
let Alpha2 =
match ((knots.[i+degree]-knots.[i])=0.0) with
|true-> 0.0
|false -> (knots.[i+degree]-x)/(knots.[i+degree]-knots.[i])
Alpha1*(basis x (degree-1) i knots) + Alpha2 * (basis x (degree-1) (i+1) knots)
B
干杯,斯蒂格
我正在嘗試復制的代碼:
basis <- function(x, degree, i, knots) {
if(degree == 0){
B <- ifelse((x >= knots[i]) & (x < knots[i+1]), 1, 0)
}
else {
if((knots[degree+i] - knots[i]) == 0) {
alpha1 <- 0
}
else {
alpha1 <- (x - knots[i])/(knots[degree+i] - knots[i])
}
if((knots[i+degree+1] - knots[i+1]) == 0) {
alpha2 <- 0
} else {
alpha2 <- (knots[i+degree+1] - x)/(knots[i+degree+1] - knots[i+1])
}
B <- alpha1*basis(x, (degree-1), i, knots) + alpha2*basis(x, (degree-1), (i+1), knots)
}
return(B)
}
bs <- function(x, degree=3, interior.knots=NULL, intercept=FALSE, Boundary.knots = c(0,1)) {
if(missing(x)) stop("You must provide x")
if(degree < 1) stop("The spline degree must be at least 1")
Boundary.knots <- sort(Boundary.knots)
interior.knots.sorted <- NULL
if(!is.null(interior.knots)) interior.knots.sorted <- sort(interior.knots)
knots <- c(rep(Boundary.knots[1], (degree+1)), interior.knots.sorted,rep(Boundary.knots[2], (degree+1)))
K <- length(interior.knots) + degree + 1
B.mat <- matrix(0,length(x),K)
for(j in 1:K) B.mat[,j] <- basis(x, degree, j, knots)
if(any(x == Boundary.knots[2])) B.mat[x == Boundary.knots[2], K] <- 1
if(intercept == FALSE) {
return(B.mat[,-1])
} else {
return(B.mat)
}
}
如果您想用多個x調用基,那么我可以這樣做:
首先將基礎的簽名更改為
let rec basis degree i (knots:float[]) (x:float)
像這樣為所有xs調用它:
xs |> List.map (basis degree i knots)
如果所有其他事情都按預期工作,那應該給您一個數組。 這意味着我將所有x和管道(|>)帶到函數List.map
。 List.map
接受一個函數和一個元素列表,並將該函數應用於列表中的所有元素,並返回一個已應用該函數的新列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.