2

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?

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
Alan
  • 13,686
  • 19
  • 38

2 Answers2

2
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}}

eldo
  • 67,911
  • 5
  • 60
  • 168
1

Code:

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

Output:

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

Reference:

ReplacePart

EDIT 1:
Based on comment left by @SimonWoods, please consult adjusted implementation below:

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}}

e.doroskevic
  • 5,959
  • 1
  • 13
  • 32
  • This is not what the question asks for - the idea is to apply f to the matrix element at position {2,2} – Simon Woods Nov 26 '15 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}] ? – e.doroskevic Nov 26 '15 at 18:28