1
$\begingroup$

I'm new to all these stuff, so apologizes if this is so simply to any of you, or if it is already asked (I have been looking for several hours, but didn't succeed in finding something similar).

I have a few hundreds vectors of different length but with ordered entries. I want to pick the entries such that, given the first one, the nexts ones are bigger (or equal) than, let's say 3, w.r.t. the previous accepted

A = {10, 11, 14, 16, 29};

gives

{10, 14, 29}
$\endgroup$
1
$\begingroup$

just choose s and t and the starting element x

F[s_List, t_Integer] := Module[{l, a, x = 1},
l = s[[x]];
a = {};
Quiet@While[l <= Last@s, f = s - l; AppendTo[a, l];
l = Select[f, # >= t &][[1]] + l];
a]   

F[{10, 11, 14, 16, 29}, 3]

{10, 14, 29}

here is a test for t=4 starting from the first position x=1

test= Sort@RandomChoice[Range@100, 20]  
F[test,4]

{6,9,14,18,21,30,36,44,44,45,52,70,71,74,82,88,90,92,93,96}
{6,14,18,30,36,44,52,70,74,82,88,92,96}

|improve this answer|||||
$\endgroup$
0
$\begingroup$

This tiny compiled function should do:

cf = Compile[{{a, _Integer, 1}, {d, _Integer}},
   Block[{bag, threshold, buffer},
    buffer = Compile`GetElement[a, 1];
    bag = Internal`Bag[{buffer}];
    threshold = buffer + d;
    Do[
     buffer = Compile`GetElement[a, i];
     If[buffer >= threshold,
      threshold = buffer + d;
      Internal`StuffBag[bag, buffer]
      ];
     , {i, 2, Length[a]}];
    Internal`BagPart[bag, All]
    ],
   CompilationTarget -> "C",
   RuntimeAttributes -> {Listable},
   Parallelization -> True,
   RuntimeOptions -> "Speed"
   ];

Usage example:

cf[{10, 11, 14, 16, 29}, 3]

{10, 14, 29}

This function is listable, so it can process lists of list quite efficiently:

A = Sort /@ RandomInteger[{0, 100}, {100000, 100}];
cf[A, 3]; // AbsoluteTiming // First

0.035603

|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.