# Replace matrix rows conditionally while avoiding For loop

I have the following variables:

myMatrix={{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0}}
myIndices={1,3}


I need to replace the rows myIndices of myMatrix with rows that contain a 1 at the position of the row number. The final result should be:

myMatrixFinal={{1,0,0},{0,0,0},{0,0,1},{0,0,0},{0,0,0},{0,0,0}}


How can I do this functionally, without a For loop? Thank you!

Try this:

Set[myMatrix[[#, #]], 1] & /@ myIndices;


Or:

ReplacePart[myMatrix, {{#, #} & /@ myIndices -> 1}]


Or:

SparseArray[({#, #} -> 1 & /@ myIndices), Dimensions@myMatrix] // Normal

• @space_voyager Thanks for the accept, but I'd wait for a while and see what other people come up with. There's a whole lot of smarter folks than me here!
– kale
Commented Jul 30, 2015 at 20:47
• Alright! I'm still not used to people here being so open to what others have in store! Commented Jul 31, 2015 at 2:31
f = MapAt[1&, #, Thread[{#2, #2}]] &;

f[myMatrix, myIndices]
(* {{1, 0, 0}, {0, 0, 0}, {0, 0, 1}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}} *)

myMatrixFinal = ReplacePart[myMatrix, {#, #} & /@ myIndices -> 1]

(myMatrix[[#, #]] = 1) & /@ myIndices;

• Pure functions with assignments-as-side-effect tickle my fancy for some reason. Commented Jul 31, 2015 at 2:12
• In my mind, they're scary things - I even fear to use them in Scan. A "pure function" is meant to be "pure"! Commented Jul 31, 2015 at 7:14
m = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}};

p = {1, 3};


Using ReplaceAt (new in 13.1) and ReplicateLayer (new in 11.1)

ReplaceAt[_ :> 1, ReplicateLayer[2, 2] @ p] @ m


{{1, 0, 0}, {0, 0, 0}, {0, 0, 1}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}}

Another way using SubsetMap:

m = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}};

p = {1, 3};

SubsetMap[{1, 1} &, m, Floor@ReplicateLayer[2, 2]@p]

(*{{1, 0, 0}, {0, 0, 0}, {0, 0, 1}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}}*)