# Replacing an element of a matrix by a function of that same element

I want to replace an element of a matrix by a function of its current value. The code I'm using is as follows

T = {{2, 3}, {3, 2}, {1, 4}}
KNeeds = Transpose[T][[2]]
pos = Flatten[{Position[KNeeds, Min[KNeeds]], 2}]
ReplacePart[T, pos -> T[[pos[[1]]]] - Epsilon]]


I was hoping to obtain {{2, 3}, {3, 2-Epsilon}, {1, 4}}, but I get {{2, 3}, {3, {3 - Epsilon, 2 - Epsilon}}, {1, 4}}.

I've also tried ReplacePart[T, pos -> T[[pos]] - Epsilon]], but then I get {{2, 3}, {3, {{3 - Epsilon, 2 - Epsilon}, {3 - Epsilon, 2 - Epsilon}}}, {1, 4}}.

• MapAt[# - \[Epsilon] &, T, pos] ? Commented Oct 15, 2018 at 8:52
• Works like a charm, thanks @b.gatessucks Commented Oct 15, 2018 at 8:58

pos = Cases[Position[T, Min[T[[All, 2]]]], {_, 2}]

ReplacePart[T, Thread[pos -> Extract[T, pos] - Epsilon]]

MapAt[# - Epsilon &, T, pos]

• (Hopefully my gedanken Mathematica got this okay.) Commented Oct 15, 2018 at 9:04
• Wouldn't your code replace all ´2´ in the matrix by ´2-Epsilon´? This is not what I intended @J.M. is computer-less Commented Oct 15, 2018 at 14:28
• It shouldn't; that is what Cases[] is for. Did you look at the output of pos? Commented Oct 15, 2018 at 15:02
• You're right, of course. Just to make sure I understand your code, in case the minimum value appeared on several rows of column 2 , it would replace all of them, woudn't it? @J.M. is computer-less Commented Oct 16, 2018 at 7:37
• Right, m = Min[T[[All, 2]]] will yield the minimum value in the second column of T, and then Position[T, m] will give (possibly multiple) locations of the minimum in the whole of T. You can then use Cases[] to filter out what you want. Commented Oct 16, 2018 at 8:00

Try this:

T /. {a_, 2} -> {a, 2 - epsilon}

(*  {{2, 3}, {3, 2 - epsilon}, {1, 4}}  *)


Have fun!

ReplacePart[T, pos -> T[[## & @@ pos]] - ϵ]


{{2, 3}, {3, 2 - ϵ}, {1, 4}}

Also

T = {{2, 3}, {3, 2}, {1, 4}};
T[[## & @@ pos]] = T[[## & @@ pos]] - ϵ;
T


{{2, 3}, {3, 2 - ϵ}, {1, 4}}

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


Using PositionSmallest (new in 13.2) and ReplaceAt (new in 13.1)

p = Append[-1] @ PositionSmallest[Last /@ list]


{2, -1}

ReplaceAt[a_ :> a - ϵ, p] @ list


{{2, 3}, {3, 2 - ϵ}, {1, 4}}

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


Using SequencePosition and SubsetMap:

p = SequencePosition[#, {{_, Min@#[[All, 2]]}}] &@list;

SubsetMap[# - ϵ &, list, p]

(*{{2, 3}, {3, 2 - ϵ}, {1, 4}}*)