Change matrix elements at specific locations?

Using RuleDelayed instead of Rule in ReplacePart:

ReplacePart[a, {i_, i_} :> 2 a[[i, i]]]

or, using Part assignment as in:

(a[[#, #]] = 2 a[[#, #]]) & /@ Range[3]
Table[a[[i, i]] == 2 a[[i, i]], {i, 1, 3}]

or, using MapAt:

MapAt[2 # &, a, Table[{j, j}, {j, 3}]]

or, using MapIndexed:

MapIndexed[If[SameQ @@ #2, 2 #, #] &, a, {2}]
(* or MapIndexed[If[Equal @@ #2, 2 #, #] &, a, {2}] *)

all give

(* {{2, 2, 3}, {4, 10, 6}, {7, 8, 18}} *)

By the way, my favorite is your a*SparseArray[{i_,i_} -> 2, {3,3}, 1].


a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

f = # + #*IdentityMatrix[[email protected]#] &;

[email protected]

(* {{2, 2, 3}, {4, 10, 6}, {7, 8, 18}} *)