1
$\begingroup$

Given a matrix defined through Grid, how can I specify the background color of entire rows based of the values of the cell in a specific column? For example, I have the following matrix:

 matrix = RandomInteger[{0, 10}, {5, 4}];
 Grid[matrix, Frame-> All];

{"0", "2", "5", "7"},
{"6", "2", "7", "1"},
{"0", "9", "10", "8"},
{"7", "2", "6", "5"},
{"6", "8", "10", "3"}

and I want to set a background color for the rows which are containing values bigger than 6 on the 3rd column.

$\endgroup$
1
$\begingroup$
SeedRandom[420];
matrix = RandomInteger[{0, 10}, {5, 4}];
colorrules = Table[n -> If[matrix[[n, 3]] < 6, Gray, Pink], {n, 1, 5}];
Grid[matrix, Frame -> All, Background -> {None, colorrules}]

Mathematica graphics

$\endgroup$
  • $\begingroup$ Thanks a lot. Could you explain me the meaning of "& /@ Range[5]? $\endgroup$ – Conrad May 27 '16 at 9:10
  • 1
    $\begingroup$ @Conrad - there I was using a pure function (the # and & symbols) and Mapping that pure function (the /@ notation) onto the list {1,2,3,4,5} (the Range[5]). I was trying to write it shorter than Table[n -> If[matrix[[n, 3]] < 6, Gray, Pink], {n, 1, 5}] but I think it's easier to use the Table and more clear so I will change it. $\endgroup$ – Jason B. May 27 '16 at 9:15
1
$\begingroup$
matrix = RandomInteger[{0, 10}, {5, 4}];

Grid[matrix, 
Background -> {None, 
DeleteCases[
Table[Which[matrix[[i, 3]] > 6, i -> Red], {i, 1, 
Length[matrix]}], Null]}, Frame -> All]

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.