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

2 Answers 2

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$
0
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 and acknowledge you have read our privacy policy.

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