I have a set of positions where I want to slice a list of numbers. If I Total
the values in that list, and they are greater than or equal to 1, I want to remember the coordinates of the slice.
The following function implements the above, but when If evaluates to False
, and empty list is appended to the coordinates I wanted to remember.
I understand it is possible to just simply remove the empty lists after the whole data structure is assembled, but I do not want to do this. The reason is that I am dealing with very large data sets and want to minimize the number of unnecessary operations. With this in mind, it would be ideal if the empty list was never appended in the first place. Link to Similar Question
tstFunc[pos_, lst_] :=
Module[{realPulses = {}, start = pos[[1]], stop = pos[[2]], tot = 0},
tot = Total[ lst[[start ;; stop]] ];
If[tot >= 1,
realPulses = Flatten[Append[realPulses, pos]]];
realPulses]
pos = {{1, 5}, {10, 11}, {15, 20}}
highArray = SparseArray[# -> 1 & /@ {4, 5, 10, 11}, 20]
highSlices = tstFunc[#, highArray] & /@ pos
Gives Output
{{1, 5}, {10, 11}, {}}
I have taken the answers so far and compared their timing, since I tagged the question with timing.
AbsoluteTiming[tstFuncEldo[pos, highArray]]
{0.000237271, {{1, 5}, {10, 11}}}
AbsoluteTiming[tstFuncGeorge[#, highArray] & /@ pos]
{0.000286419, {{1, 5}, {10, 11}}}
AbsoluteTiming[tstFuncXavier[#, highArray] & /@ pos]
{0.000388954, {{1, 5}, {10, 11}}}
Can any one comment as to why my 'If' statement is appending an empty list?
Note: @eldo solution is the only one that gives the correct result for pos = {{11,22}, {270, 270}, {291, 291}}
highArray
should belist
? $\endgroup$tstFunc2[pos_, lst_] := If[Plus @@ Take[lst, pos] >= 1, pos, Unevaluated@Sequence[]];
useful for "minimiz[ing] the number of unnecessary operations". $\endgroup$highArray
is a sparse array. Now I have edited. $\endgroup$Take[list,{a,b}]
andlist[[{a,b}]]
are not the same.Take
is what you want here... (the latter happens to give the same result for this example) $\endgroup$