ReplaceIf
Conditionally replaces values in a container.
Syntax
-
ReplaceIf(X, p, y[, n])
-
X
is a container -
p
is a predicate -
y
is any object -
n
is a positive integer
-
Description
If X
is a container, p
a boolean-valued function on X
, and y
any object, then ReplaceIf(X, p, y)
returns X
with all elements x
for which p(x)
is true
replaced by y
. ReplaceIf(X, p, y, n)
replaces elements at level n
, with level n = 1
being X
itself.
Examples
A ≔ RandomIntMatrix(10, 0, 10)
⎛0 6 2 5 7 9 4 5 3 7⎞ ⎜8 5 5 8 2 2 2 9 9 6⎟ ⎜0 0 5 6 0 2 2 8 9 4⎟ ⎜7 4 0 8 0 9 0 1 3 5⎟ ⎜4 1 9 4 9 5 5 0 6 9⎟ ⎜8 6 6 2 9 3 6 9 1 6⎟ ⎜9 0 2 2 7 7 4 4 1 5⎟ ⎜0 2 8 1 6 7 3 2 7 6⎟ ⎜6 1 9 6 1 4 1 6 1 0⎟ ⎝4 7 7 1 2 4 5 0 3 8⎠
ReplaceIf(A, odd, 0)
⎛0 6 2 0 0 0 4 0 0 0⎞ ⎜8 0 0 8 2 2 2 0 0 6⎟ ⎜0 0 0 6 0 2 2 8 0 4⎟ ⎜0 4 0 8 0 0 0 0 0 0⎟ ⎜4 0 0 4 0 0 0 0 6 0⎟ ⎜8 6 6 2 0 0 6 0 0 6⎟ ⎜0 0 2 2 0 0 4 4 0 0⎟ ⎜0 2 8 0 6 0 0 2 0 6⎟ ⎜6 0 0 6 0 4 0 6 0 0⎟ ⎝4 0 0 0 2 4 0 0 0 8⎠
compute(RandomIntMatrix(4, 1, 10), n, 1, 5)
⎛1 5 9 7⎞ ⎛1 3 1 8⎞ ⎛2 7 6 8⎞ ⎛8 2 2 6⎞ ⎛8 3 4 8⎞ ⎜6 9 6 7⎟ ⎜9 9 3 5⎟ ⎜2 7 7 6⎟ ⎜2 2 4 2⎟ ⎜8 1 9 9⎟ ⎜4 7 7 2⎟ ⎜1 6 6 9⎟ ⎜3 4 8 9⎟ ⎜9 1 8 1⎟ ⎜8 6 9 7⎟ ⎝6 8 9 9⎠ ⎝3 3 5 2⎠ ⎝4 9 4 7⎠ ⎝2 5 9 1⎠ ⎝8 2 4 9⎠
ReplaceIf(ans, odd, 0, 2)
⎛0 0 0 0⎞ ⎛0 0 0 8⎞ ⎛2 0 6 8⎞ ⎛8 2 2 6⎞ ⎛8 0 4 8⎞ ⎜6 0 6 0⎟ ⎜0 0 0 0⎟ ⎜2 0 0 6⎟ ⎜2 2 4 2⎟ ⎜8 0 0 0⎟ ⎜4 0 0 2⎟ ⎜0 6 6 0⎟ ⎜0 4 8 0⎟ ⎜0 0 8 0⎟ ⎜8 6 0 0⎟ ⎝6 8 0 0⎠ ⎝0 0 0 2⎠ ⎝4 0 4 0⎠ ⎝2 0 0 0⎠ ⎝8 2 4 0⎠