2

Consider this simple code:

Grid[RandomInteger[{0, 1}, {10, 10}], Background -> LightBlue]

output

Is it possible to modify the code so that the background only apply for certain entries of the matrix, e.g. only for non zero entries?

Sukan
  • 455
  • 3
  • 7

2 Answers2

6
Grid[Item[#, Background -> If[# == 1, Blue]] & /@ # & /@ RandomInteger[{0, 1}, {10, 10}]]

Mathematica graphics

Grid[RandomInteger[{0, 1}, {10, 10}]] /. 1 -> Item[1, Background -> Blue]

Mathematica graphics

Grid[m = RandomInteger[{0, 1}, {10, 10}], 
    Background -> {None, None, Thread[Position[m, 1] -> Blue]}]

Mathematica graphics

kglr
  • 394,356
  • 18
  • 477
  • 896
4
r = RandomInteger[{0, 1}, {10, 10}];
bg = Thread[SparseArray[r]["NonzeroPositions"] -> LightBlue];
Grid[r, Background -> {None, None, bg}]

enter image description here

ubpdqn
  • 60,617
  • 3
  • 59
  • 148