# ReplacePart with processed value [closed]

To illustrate, suppose I want to change the {2,2} element of a matrix. If I know the replacement value, I can just make the replacement.

ReplacePart[{{1, 2}, {3, 4}}, {2, 2} -> 5]


But what if I need to process the value to get its replacement? Of course, I could create a symbol and process it.

mA = {{1, 2}, {3, 4}}
mA[[2, 2]] = f[mA[[2,2]]]


But I'd rather work directly with the value and not create a new symbol. Possible?

• Take a look at MapAt.
– Kuba
Nov 26, 2015 at 16:00
• Can it be something like: ReplacePart[{{1, 2}, {3, 4}}, {2, 2} -> f[#]] &[(value)] Nov 26, 2015 at 16:05
• @Alan, as a sort of delusions, mA[[2, 2]] = mA[[2, 2]] // Function[x, x + 1]; mA Nov 26, 2015 at 20:06
• worth noting link Nov 26, 2015 at 20:21

list = {{1, 2}, {3, 4}};

process[x_] := x + 1

ReplacePart[list, # :> process@Extract[list, #]] &[{2, 2}]


{{1, 2}, {3, 5}}

As commented by @Kuba the more natural choice would be

MapAt[process, list, {2, 2}]


{{1, 2}, {3, 5}}

• You're processing 5, not the 4 in position {2, 2} Nov 26, 2015 at 16:45

Code:

ReplacePart[{{1, 2}, {3, 4}}, {2, 2} -> f[#]] &[5]


Output:

{{1, 2}, {3, f[5]}}

Reference:

ReplacePart

EDIT 1:

Code:

(*Sample*)
list = {{1, 2}, {3, 4}};

(*Dummy function*)
f[x_] := x + 1;

(*Operation*)
ReplacePart[list, # -> f[list[[2, 2]]]] &[{2, 2}]


Output:

{{1, 2}, {3, 5}}

• This is not what the question asks for - the idea is to apply f to the matrix element at position {2,2} Nov 26, 2015 at 17:35
• @SimonWoods I must have misunderstood the OPs question, would following adjustment be a better fit: ReplacePart[{{1, 2}, {3, 4}}, # -> f[#]] &[{2, 2}] ? Nov 26, 2015 at 18:28