1
$\begingroup$

I am trying to compile something similar to the following:

test = Compile[{{data, _Real, 1}}, 
  First@FirstPosition[data, _?(# > 0 &)]]

However I get the following error, which I don't understand:

Compile::part: Part specification FirstPosition[data,_?(#1>0&)][[1]] cannot be compiled since the argument is not a tensor of sufficient rank. Evaluation will use the uncompiled function.

Is there a way to make this work?

$\endgroup$
  • 2
    $\begingroup$ The function FirstPosition simply will not compile to lower level code, so the only way to do this, is to write your own iterative loop from scratch. A simple Do loop with a Break should suffice. $\endgroup$ – Sjoerd Smit Dec 6 '19 at 22:25
  • $\begingroup$ Or a While loop... $\endgroup$ – Henrik Schumacher Dec 7 '19 at 6:08
3
$\begingroup$

As Sjoerd notes, you can't Compile pattern matching functions like FirstPosition. On the other hand, this will work for what you're trying to do:

test =
  Compile[{{data, _Real, 1}},
   MapIndexed[
    (If[# > 0, Return[#2[[1]]]]; 1) &,
    data
    ];
   -1
   ];

test@RandomReal[{-1, .01}, 100]

-1

test@RandomReal[{-1, .01}, 100]

46
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.