If I have a list
input={-12,-3,0,1,4,-23)
how can I set the elements greater than 0 to be zero, so the output is
output={-12,-3,0,0,0,-23}
If I have a list
input={-12,-3,0,1,4,-23)
how can I set the elements greater than 0 to be zero, so the output is
output={-12,-3,0,0,0,-23}
Hello David,
Here are three ways:
input = {-12, -3, 0, 1, 4, -23} /. x_ /; x > 0 -> 0
If[# > 0, 0, #] & /@ {-12, -3, 0, 1, 4, -23}
Replace[{-12, -3, 0, 1, 4, -23}, x_ /; x > 0 -> 0, {1}]
Have fun!
Thank you. That should solve my problem. The list is only 1601 elements long, so I don’t think computational time will be an issue, but I guess one is likely to be quicker than the other.
Another way
Clip[input, {-Infinity, 0}]
(* {-12, -3, 0, 0, 0, -23} *)
David,
You could use (your code)//Timing on a small portion of your data to see which is fastest before you run the whole shebang! Would love to know how it works out for you ![]()
Lori
Hi David,
One way to benchmark the performance of several functions.
Define the functions
replace1 = # /. x_ /; x > 0 :> 0 &;
replace2 = Replace[#, x_ /; x > 0 -> 0, {1}] &;
if = If[# > 0, 0, #] & /@ # &;
clip = Clip[#, {-Infinity, 0}] &;
Verify that one function returns the expected result
input = {-12, -3, 0, 1, 4, -23};
replace1@input
(* {-12, -3, 0, 0, 0, -23} *)
Verify that they all return the same result
replace1[#] == replace2[#] == if[#] == clip[#] &@input
(* True *)
Generate test data
data = Table[RandomReal[{-200, 200}, (n - 1)*1000], {n, 1, 101}];
Generate and plot the timing
funcs = {replace1, replace2, if, clip};
timings = Table[First@Timing[f@d], {f, funcs}, {d, data}];
ListLinePlot[timings, PlotLegends -> funcs]
ListLogPlot[timings, Joined -> True, PlotLegends -> funcs]