# Using two color functions in a MatrixPlot

I'm trying to use two color functions within one MatrixPlot in Mathematica. Is it possible to do this?

For example, using a very simple matrix:

test = Partition[Table[i, {i, 1, 9}], 3]


I would like to make the even numbers vary in color increasing from white to red; and the odd numbers vary in color from grey to black.

How could I do this? I know how to get the whole matrix to vary in color, but no more than this.

I am not sure I understand. Here's what I understand:

You want to use MatrixPlot, the built-in command.

Then, the following might do what you want:

With[{max = Max@#},
MatrixPlot[#,
ColorFunction -> (If[EvenQ[#], Blend[{White, Red}, #/max],
Blend[{Gray, Black}, #/max]] &),
ColorFunctionScaling -> False]] &@test


Note that I use ColorFunctionScaling -> False, such that the even/odd numbers are still such (otherwise EvenQ doesn't make much sense. The max will be used for proper scaling. The output looks as follows: • Thanks, that's exactly what I was looking for. – Rachel Sheldon Aug 19 '13 at 15:02
• Is there any way to instead of saying is this an even number, use the coordinates of the square? For instance, in my real coding, I want to pick out the squares I indicated above, but they aren't all real numbers. So I wish to pick squares (1,2), (2,1), (2,3), (3,2) and scale them accordingly. – Rachel Sheldon Aug 19 '13 at 15:05
• How do you mean, not real numbers? I am not sure I understand... we scale the 4 red sqaures according to the value there... – Pinguin Dirk Aug 19 '13 at 16:01
• Sorry that didn't make sense. So instead, of just having a table of integers, I have a table of values that are solutions of an NDSolve. I want to colour the cells that I indicated by even numbers in this example. Once I don't have the odd and even distinction, my thinking was that it would be easier to pick out the coordinates (e.g. square (1,2), (2,1) etc...) Does that make any more sense? – Rachel Sheldon Aug 19 '13 at 16:06
• I think I understand now. If you need that bit more flexibility, you might want to look at C.E.'s answer (you could stick to MatrixPlot I guess, using ColorRules or similar). Alternatively, you could use Graphic-primitives. As I still struggle to fully comprehend the problem, I am not sure how to adjust/edit – Pinguin Dirk Aug 19 '13 at 16:34

For more flexibility, we can dump MatrixPlot and proceed with its core component, Raster:

max = 5;
test = RandomReal[max, {5, 5}];

colorfunc[val_, i_, max_] := If[EvenQ[i],
Blend[{White, Red}, val/max],
Blend[{Gray, Black}, val/max]
]
colormatrix[matrix_, max_] := Partition[
MapIndexed[colorfunc[#, First@#2, max] &, Flatten[matrix]],
Dimensions[matrix][]
] /. {GrayLevel[a_] :> a {1, 1, 1}, RGBColor[b : _ ...] :> {b}};
Graphics[Raster[colormatrix[test, max]], Frame -> True] 