2
$\begingroup$

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?

$\endgroup$
  • 5
    $\begingroup$ Take a look at MapAt. $\endgroup$ – Kuba Nov 26 '15 at 16:00
  • $\begingroup$ Can it be something like: ReplacePart[{{1, 2}, {3, 4}}, {2, 2} -> f[#]] &[(value)] $\endgroup$ – e.doroskevic Nov 26 '15 at 16:05
  • $\begingroup$ @Alan, as a sort of delusions, mA[[2, 2]] = mA[[2, 2]] // Function[x, x + 1]; mA $\endgroup$ – garej Nov 26 '15 at 20:06
  • $\begingroup$ worth noting link $\endgroup$ – garej Nov 26 '15 at 20:21
2
$\begingroup$
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}}

$\endgroup$
  • $\begingroup$ You're processing 5, not the 4 in position {2, 2} $\endgroup$ – Chris Degnen Nov 26 '15 at 16:45
1
$\begingroup$

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.