Replace elements that do not match a pattern
Replace[mat, {0 -> 1, _ -> 0}, {2}]
(* or Replace[mat, {0 -> 1, Except[0] -> 0}, {2}] *)
{{1, 0, 0}, {0, 1, 0}, {1, 1, 0}}
Also
1 - Unitize @ ArrayComponents @ mat
{{1, 0, 0}, {0, 1, 0}, {1, 1, 0}}
And a variation of @Lotus's suggestion for ReplaceAll
:
mat /. {0 -> 1, Except[List, _Symbol] -> 0}
{{1, 0, 0}, {0, 1, 0}, {1, 1, 0}}
Update: Can this method be generalised to a matrix made of mixed symbols: e.g. {{a11, a12, s}, {a21,a22, -s},{t,s,-t}} and I want to keep only the s and t symbols ...
Replace
and ReplaceAll
can be used to deal with this case:
mat2 = {{a11, a12, s}, {a21, a22, -s}, {t, s, -t}};
Replace[#, Except[s | t | Times[_, s | t]] :> 0, {2}] & @ mat2
{{0, 0, s}, {0, 0, -s}, {t, s, -t}}
mat2 /. Except[s | t | Times | List, _Symbol] :> 0
{{0, 0, s}, {0, 0, -s}, {t, s, -t}}
SetAttributes[rep, Listable]
rep[_] := 0
rep[0] := 1
rep @ mat
{{1, 0, 0}, {0, 1, 0}, {1, 1, 0}}
Update
This method can easily be extended by adding new rules to rep
, f.e.:
rep[a_ /; MemberQ[{-t, t, -s, s}, a]] := a
Now
rep @ {{0, a12, s}, {a21, a22, -s}, {t, s, -t}}
{{1, 0, s}, {0, 0, -s}, {t, s, -t}}
Or:
mat={{0,a,b},{c,0,d},{0,0,e}};
Map[If[#===0,1,0]&, mat, {2}]
(* {{1,0,0},{0,1,0},{1,1,0}} *)