# Assign the Background rule in Grid (the positions can be described by a integer function)

For example, this code

Grid[Transpose[Table[{n, n^2}, {n, 1, 10}]], Frame -> All,
Background -> {{1 -> Red, 4 -> Red, 9 -> Red}}]


produces

,

in this case, the columns has column number being a square integer, i.e the 1,4,9,16,25...etc. columns

This second code does the same job:

rule = {};
Do[If[IntegerQ[Sqrt[i]], AppendTo[rule, i -> Red]], {i, 1, 10}]
Grid[Transpose[Table[{n, n^2}, {n, 1, 10}]], Frame -> All, Background -> {rule}]


or better

rule = {};
Do[AppendTo[rule, i^2 -> Red], {i, 1, 10}]
Grid[Transpose[Table[{n, n^2}, {n, 1, 10}]], Frame -> All, Background -> {rule}]


I wonder if there is a way to specify a rule, in the 3rd way, inside Grid[] directly.

-
You can use SparseArray for Background. – Kuba Feb 19 '14 at 23:13
IntegerQ[Sqrt[i]] is a given so you can just enter say Background -> {Thread[Range[5]^2 -> Red]} – Mike Honeychurch Feb 19 '14 at 23:19

Grid[Transpose[Table[{n, n^2}, {n, 1, 10}]], Frame -> All,