Probably easy and short question, I still didn't fully figure out how to easily select/delete sublists from a list. Example:
tt = {{2, 4}, {4, 8}};
I want to delete/select all the elements where the difference between them (Abs) is greater than four.
Answer
I would use either
Cases[data, {x_, y_} /; Abs[x - y] > 4]
or
With[{diff = Abs[data[[All, 1]] - data[[All, 2]]] - 4},
Pick[data, UnitStep[diff]*Unitize[diff], 1]
]
The first clearly demonstrates what you are trying to do, the second is much faster...
data = RandomInteger[{0, 100}, {10^6, 2}];
(m1 = Cases[data, {x_, y_} /; Abs[x - y] > 4]); // AbsoluteTiming
==> {2.8393092, Null}
(m2 =
With[{diff = Abs[data[[All, 1]] - data[[All, 2]]] - 4},
Pick[data,UnitStep[diff]*Unitize[diff], 1]]); // AbsoluteTiming
==> {0.1248024, Null}
m1 == m2
==> True
Assuming you are working with random data and don't expect equality, the second method can be simplified to...
Pick[data, UnitStep[Abs[data[[All, 1]] - data[[All, 2]]] - 4], 1]
Edit:
Of course if you want to delete elements where Abs[x-y] > 4 you can modify the Cases definition as
Cases[data, {x_, y_} /; Abs[x - y] <= 4]
And the Pick method by swapping out the 1 in the last argument with 0.
Comments
Post a Comment