# updating matrix elements based on a condition

I am (still) fairly new to Mathematica and trying to perform some operation on the matrix elements, say for the matrix

mat= {{0,0,0,1,2,3,1,3,0,2},{1,0,0,3,2,3,1,2,0,0},{0,1,0,1,0,3,1,2,3,2}}


and want to perform this map 0->00,1->01,2->10,3->11. (to give more context to it I want to convert the matrix mat in GF(4) to binary). It might seem straightforward but I am being unable to do this matrix operations (I tried the Replace or ReplacePart operations). Any help or suggestion would be greatly appreciated.

• mat = {{0, 0, 0, 1, 2, 3, 1, 3, 0, 2}, {1, 0, 0, 3, 2, 3, 1, 2, 0, 0}, {0, 1, 0, 1, 0, 3, 1, 2, 3, 2}} /. {0 -> "00", 1 -> "01", 2 -> "10", 3 -> "11"} or BaseForm[mat, 2] Commented Aug 7, 2015 at 15:21
• Of course, 00 is interpreted as 0 unless you are working with strings. Commented Aug 7, 2015 at 15:24
• Thanks for the help. However, if I want to obtain the resulting matrix after the mapping in the regular form like {{0, 0, 0, 0,0,0,0,1,1,0,1,1,0,1,1,1,0,0,1,0}, {1,0,0,0,0,0,1,1,1,0,0,1,1,0,0,0,0,0},{0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,1,1,0}} should I use some kind partitioning/ flatten-unflatten command? (I already tried with some of them) Commented Aug 16, 2015 at 21:52
• @march. Yes, please-it would be greatly appreciated. Thanks Commented Aug 17, 2015 at 20:26
• @reach2brb. See updated answer. Commented Aug 17, 2015 at 20:47

Here are some options for the example matrix

mat = {{0, 0, 0, 1, 2, 3, 1, 3, 0, 2}
, {1, 0, 0, 3, 2, 3, 1, 2, 0, 0}
, {0, 1, 0, 1, 0, 3, 1, 2, 3, 2}};


The following returns a list at each spot with the binary digits as elements:

list = Map[IntegerDigits[#, 2, 2] &, mat, {2}]
(* {{{0, 0}, {0, 0}, {0, 0}, {0, 1}, {1, 0}, {1, 1}, {0, 1}, {1, 1}, {0, 0}, {1, 0}}
, {{0, 1}, {0, 0}, {0, 0}, {1, 1}, {1, 0}, {1, 1}, {1}, {1, 0}, {0, 0}, {0, 0}}
, {{0, 0}, {0, 1}, {0, 0}, {0, 1}, {0, 0}, {1, 1}, {0, 1}, {1, 0}, {1, 1}, {1, 0}}} *)


To invert this, do

Map[FromDigits[#, 2] &, list, {2}]


This one takes the previous and combines the digits into a string:

list = Map[StringJoin @@ ToString /@ IntegerDigits[#, 2, 2] &, mat, {2}]
(* {{"00", "00", "00", "01", "10", "11", "01", "11", "00", "10"}
, {"01", "00", "00", "11", "10", "11", "01", "10", "00", "00"}
, {"00", "01", "00", "01",  "00", "11", "01", "10", "11", "10"}} *)


To invert this, do

Map[FromDigits[ToExpression /@ Characters[#], 2] &, list, {2}]


This one writes it in base form explicitly:

list = Map[BaseForm[#, 2] &, mat, {2}]


but it doesn't give both digits and it's purely for display purposes. To invert that do

list /. BaseForm[a_, _] :> a