2
$\begingroup$

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?

$\endgroup$
  • $\begingroup$ Closely related: (31152) @kglr $\endgroup$ – Mr.Wizard May 14 '16 at 1:10
6
$\begingroup$
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

$\endgroup$
4
$\begingroup$
r = RandomInteger[{0, 1}, {10, 10}];
bg = Thread[SparseArray[r]["NonzeroPositions"] -> LightBlue];
Grid[r, Background -> {None, None, bg}]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.