Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

For example, this code

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

produces

enter image description here,

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.

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

1 Answer 1

For the record:

Grid[Transpose[Table[{n, n^2}, {n, 1, 10}]], Frame -> All, 
     Background -> {Normal @ SparseArray[i_ :> Red /; IntegerQ[Sqrt[i]], 10, White]}]

Of course Mike`s way is way shorter so I'd use it here but I think this one can be used im more complicated cases.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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