in reply to PDL, applying function

My approach would start from setting the zeroes to randomly 1 or 0 first, then using https://metacpan.org/pod/PDL::Primitive#clip (untested):
$inds = $x->whichND($x == 0); $x->indexND($inds) .= ($x->random < 0.5)->indexND($inds); $x->inplace->clip(0,1);
This would obviously benefit enormously from loop fusion or making your own custom PDL operation.

Replies are listed 'Best First'.
Re^2: PDL, applying function
by Anonymous Monk on May 22, 2022 at 07:03 UTC

    clip is nice. I think first 2 lines can be shorter and more efficient: no need to generate possibly ginormous random array and then index into

    $view = $x->whereND($x == 0) $view .= $view->random < .5
      A great option! I'll confess I was a bit tired, so after figuring out something that would broadcast over n-dimensional inputs better than using where, I stopped. Your code is clearly better.
Re^2: PDL, applying function
by etj (Priest) on Aug 16, 2024 at 15:12 UTC
    Note from the future: to most accurately reflect the original requirement, one would need to clip first, since anything less than 0 would be set to 0, then any 0s (including the new ones) get set to a randomised 1/0.