How can I suppress zero or nonzero values in a matrix?

You can also use MapAt with Invisible or Style[#,White]&:

f1 = MatrixForm[MapAt[Invisible, #, Position[#, Except[#2], {2}, Heads->False]]] &;(*or*)
f1 = MatrixForm[MapAt[Style[#,White]&, #, Position[#, Except[#2], {2}, Heads->False]]] &;

Example:

m = RandomInteger[5, {5, 5}];
Row[Prepend[f1[m, #] & /@ {1, 2, 1 | 2}, MatrixForm[m]], Spacer[5]]

enter image description here

Update: Using Manipulate to toggle the elements to show:

mf1 = Manipulate[f1[#, Alternatives @@ show] // Style[#, 20] &, 
                 {{show, {1}}, Union@Flatten@#, TogglerBar}, Alignment -> Center] &;

Example:

m = RandomChoice[Range[0, 20], {5, 10}];
mf1@m

enter image description here


f[x_List, n_] := (x /. y_ /; y != n -> " ") // MatrixForm

f[{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, 7]

If you need to display only elements in list n, then use:

g[x_List, n_List] := x /. y_ /; (MemberQ[Complement[Flatten[x], n], y]) -> " " // 
  MatrixForm

g[{{1,2,3},{4,5,6},{7,8,9}}, {3,7}]

I'm sure there's a more elegant way to do this last transformation, but the obvious ones involving !MemberQ[n,y] or FreeQ[n,y] somehow didn't work.


Here's a variation you might find useful:

fn[a_?ArrayQ, x_] :=
  Replace[a, p : Except[x] :> Style[p, White], {ArrayDepth@a}] // MatrixForm

Now:

fn[IdentityMatrix[3], 1]

enter image description here

But because the non-selected elements are only styled white they appear when selected:

enter image description here