views:

57

answers:

1

In Mathematica the command Select only lets define a selection criterion for each element of a list on its own.

I want to specify a criterion that is dependend of a function of the previous and/or next element and a function on all elements, respectively. The first and last element cannot be tested that way, but they should be selected anyway.

Doing that iteratively probably would not be a problem, I want to try it functional first.

I would imaging using it somehow like that:

Select[list,FirstQ||LastQ,Func1[#-1,#]&&Func2[#,#1]&&Func3[list]&]
+3  A: 

I suggest using the Partition function. To get each element of a list grouped with its immediate neighbors you can do this

Partition[{a,b,c,d,e}, 3, 1]

to get this:

{{a,b,c}, {b,c,e}, {c,d,e}}

Knowing that, we can make a "select with neighbors" function that roughly matches your spec:

SelectWN[list_, firstq_, lastq_, trinaryfunc_] := Join[
  If[firstq, {First@list}, {}], 
  Select[Partition[list, 3, 1], trinaryfunc@@#&][[All,2]], 
  If[lastq, {Last@list}, {}]]

Note that in the arguments to trinaryfunc, #2 is the list element itself, #1 is the left neighbor, and #3 is the right neighbor. It would be nice to generalize this to use any number of neighbors, not just the immediate neighbors, but then you'd want a better way to refer to them than the analog of {#1, #2, #3}.

dreeves
Thank you for your great help. I used it for another problem I had.Thing is I realized my premises were wrong. I cannot do what I imagined in a static way like that.Iterating from left to right, I need to check all 3-groups, yes, but if the trinaryfunc condition does not hold, I would kick out that element n and repeat the testcondition with the new 3-group consisting of the elements n-1, n+1 and n+2.Maybe I could repeat the SelectWN function until no changes happen anymore, but that would result in double-calculation for final 3-groups.I guess the iterative approach is the one to go here.
fabb