"Select" comparing neighboring elements in Mathematica
In Mathematica the command Sele开发者_高级运维ct 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]&]
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}.
精彩评论