Message Boards Message Boards

0
|
5453 Views
|
5 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Set to zero elements of a list greater than zero

Posted 4 years ago

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}
POSTED BY: David Kirkby
5 Replies
Posted 4 years ago

Another way

Clip[input, {-Infinity, 0}]
(* {-12, -3, 0, 0, 0, -23} *)
POSTED BY: Rohit Namjoshi
Posted 4 years ago

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.

POSTED BY: David Kirkby

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 :D

Lori

POSTED BY: Lori Johnson
Posted 4 years ago

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]

enter image description here

enter image description here

POSTED BY: Rohit Namjoshi

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!

POSTED BY: Lori Johnson
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract