The following code flips the bits of a binary-valued matrix.
I realise that the positions of diagonal elements (form {i,i}) can be easily generated with Table or another Mathematica function. I don't want to use this fact. I aim to learn about applying functions to elements in specific positions, using patterns to identify the positions.
The following code for flipping the bits on diagonal positions of a matrix has been written in that spirit:
Test to identify diagonal positions:
diagonalPositionTest[p_] := MatchQ[p, {i_, i_}]
Determining the positions of diagonal elements using MapIndexed:
helpMapIndexed[f_, m_] := MapIndexed[{#1, f[#2]} &, m, {2}]
matrixAnnotated = helpMapIndexed[diagonalPositionTest, M]
Flipping the diagonal-bits
matrixAnnotated /. {{x_, True} -> 1 - x, {x_, False} -> x}
The code can be tested on a binary-valued matrix:
M = IdentityMatrix[4] /. {0 :> RandomInteger[{0, 1}],
1 :> RandomInteger[{0, 1}]}
Can the above solution be coded in a different way?
I don't mean using the fact that diagonal positions are of a trivial form (eliminating the pattern-test).
I mean: is there a more direct route (or more efficient code) to produce the same result using a Mathematica command that
- makes use a pattern to identify particular positions
- with the aim to replace the elements in those selected positions with new elements
- (where these new elements are computed via a function application).
Or is MapIndexed the "right" approach (given the above aims)?
Do[M = MapAt[1 - # &, M, {i, i}], {i, 4}]
$\endgroup$