as.logical(advector)

32 views
Skip to first unread message

Abe Solberg

unread,
May 4, 2026, 10:00:14 AMMay 4
to TMB Users
Hi All,

I'm trying to use a combination of differentiable max and as.logical to identify the first index in a vector with a value above 0. 

max2 = function(x,y){(x + y + abs(x - y)) / 2}
idx <- sapply(advec , max2 , 0 , simplify = TRUE)
value <- vec[as.logical(idx)][1] 

I'm finding that as.logical returns TRUE for all idx, even when the value is 0 (unlike as.logical(0L), which returns FALSE. 

I imagine this is expected behavior in RTMB, but has anyone dealt with a similar problem and come up with a solution? For my issue specifically, advec is constantly increasing so idx will be all 0's until the first positive value. I'd prefer not to use use RTMB:::getValues.  

Thanks in advance,
Abe

Kasper Kristensen

unread,
May 4, 2026, 12:30:18 PMMay 4
to TMB Users
How about:

f <- function(x) x[findInterval(AD(0), x)]

Abe Solberg

unread,
May 5, 2026, 6:07:07 AMMay 5
to TMB Users
Thanks for the idea, Kasper! This works, but has a somewhat unexpected outcome. 

I can use the output of f to isolate the value x[f(x)]. However, if I use the output to try and replace a value x[f(x)] <- AD(0) for example, I get an error "invalid subscript type 'complex'". ADOverload is enabled for  "[<-". I'm having a somewhat difficult time circumventing this. Among others, I've tried c(head(x , f(x)-1) , AD(0) , tail(x , f(x)-1)), x[cumsum(rep(1 , f(x)]...  which also fail. 

Thanks again for taking a look. 
-Abe
Reply all
Reply to author
Forward
0 new messages