-
Notifications
You must be signed in to change notification settings - Fork 0
/
pwlin.R
51 lines (46 loc) · 1.32 KB
/
pwlin.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#Implements a piecewise linear function
#
#Args
#x A vector of values to evaluate the function at
#xbp A vector of strictly increasing values, the x-axis breakpoint values of the function
#ybp A vector of the same length, the values of the function at the breakpoints
#
#Output
#A vector of values, NA for indices for which x was outside the range min(xbp) to
#max(xbp)
pwlin<-function(x,xbp,ybp)
{
#some small amount of error checking
if (any(diff(xbp)<=0))
{
stop("Error in pwlin: xbp values must be strictly increasing")
}
#receptacle for results
res<-NA*numeric(length(x))
#now map each of the values of x that can be mapped
inds<-which(x>=xbp[1] & x<=xbp[length(xbp)])
if (length(inds)>0)
{
for (counter in 1:length(inds))
{
thisx<-x[inds[counter]]
#wind1<-which(xbp<=thisx)
#wind2<-which(xbp>=thisx)
#if (length(wind1)==0 || length(wind2)==0)
#{
# save(x,xbp,ybp,file="ErrorChecker.RData")
# stop("Error in pwlin, file saved for debugging")
#}
ilo<-max(which(xbp<=thisx))
ihi<-min(which(xbp>=thisx))
if (ilo==ihi)
{
res[inds[counter]]<-ybp[ilo]
}else
{
res[inds[counter]]<-((thisx-xbp[ilo])/(xbp[ihi]-xbp[ilo]))*(ybp[ihi]-ybp[ilo])+ybp[ilo]
}
}
}
return(res)
}