4
$\begingroup$

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!

$\endgroup$

6 Answers 6

9
$\begingroup$

Try this:

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

Or:

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

Or:

SparseArray[({#, #} -> 1 & /@ myIndices), Dimensions@myMatrix] // Normal
$\endgroup$
2
  • $\begingroup$ @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! $\endgroup$
    – kale
    Commented Jul 30, 2015 at 20:47
  • $\begingroup$ Alright! I'm still not used to people here being so open to what others have in store! $\endgroup$ Commented Jul 31, 2015 at 2:31
6
$\begingroup$
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}} *)
$\endgroup$
3
$\begingroup$
myMatrixFinal = ReplacePart[myMatrix, {#, #} & /@ myIndices -> 1]
$\endgroup$
3
$\begingroup$
(myMatrix[[#, #]] = 1) & /@ myIndices;
$\endgroup$
2
  • $\begingroup$ Pure functions with assignments-as-side-effect tickle my fancy for some reason. $\endgroup$
    – march
    Commented Jul 31, 2015 at 2:12
  • 1
    $\begingroup$ In my mind, they're scary things - I even fear to use them in Scan. A "pure function" is meant to be "pure"! $\endgroup$ Commented Jul 31, 2015 at 7:14
2
$\begingroup$
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}}

$\endgroup$
0
$\begingroup$

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}}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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