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$
9
$\begingroup$

Try this:

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

Or:

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

Or:

SparseArray[({#, #} -> 1 & /@ myIndices), Dimensions@myMatrix] // Normal
| improve this answer | |
$\endgroup$
  • $\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 Jul 30 '15 at 20:47
  • $\begingroup$ Alright! I'm still not used to people here being so open to what others have in store! $\endgroup$ – space_voyager Jul 31 '15 at 2:31
5
$\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}} *)
| improve this answer | |
$\endgroup$
3
$\begingroup$
myMatrixFinal = ReplacePart[myMatrix, {#, #} & /@ myIndices -> 1]
| improve this answer | |
$\endgroup$
3
$\begingroup$
(myMatrix[[#, #]] = 1) & /@ myIndices;
| improve this answer | |
$\endgroup$
  • $\begingroup$ Pure functions with assignments-as-side-effect tickle my fancy for some reason. $\endgroup$ – march Jul 31 '15 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$ – Patrick Stevens Jul 31 '15 at 7:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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