Reputation: 1729
I'm working with an array from a 3d array, and with lots of previous help here, got a very nice simple elegant solution :
## Reset 44 and 33 to 4 and 3 respectively
replace!(@view(Pop[end, :, 1]), 33=>3, 44=>4)
Now if I wanted to do the replacement on a probability basis, where I would supply the probability, can I do it in one line or do I need to write a function to interrogate the small array, and then loop through and do the substitutions based on the probability? So for example if I wanted to replace 33=>3 with a probability of 0.7, so the sub is made on 70% of occurrences of 33, and replace 44=>4 with a different probability, eg 0.85 how would I write this? Thx. J
Upvotes: 0
Views: 38
Reputation: 12654
Here's one possible solution, which is pretty efficient, only a few times slower than a deterministic replace!
function rreplace!(xs, args...)
@inbounds for i in eachindex(xs)
val = xs[i]
for tup in args
if val == tup[1][1]
rand(tup[2]) && (xs[i] = tup[1][2])
break
end
end
end
return xs
end
You can call it like this:
rreplace!(xs, (33=>3, Bernoulli(0.7)), (44=>4, Bernoulli(0.85)))
You could of course use other distributions aside from Bernoulli
, as long as they return either true
or false
.
In your particular question, it would be
rreplace!(@view(Pop[end, :, 1]), (33=>3, Bernoulli(0.7)), (44=>4, Bernoulli(0.85)))
Upvotes: 2