# Coloring elements of a block of a matrix

Assume I have the matrix

A = [ a_11 a_12 a_13 a_14; a_21 a_22 a_23 a_24; a_31 a_23 _a33 a_34; ]

where a_ij are numbers and I want to draw in red color the elements of the 3 x 3 block A(1:3, 1:3). Is there an easy way to draw them at once instead of using the command \textcolor{red}{a_11}, \textcolor{red}{a_22} e.t.c?

TeX is a macro language. The lengthy expression \textcolor{red}{a_{12}} can be abbreviated with as simple macro definition, e.g.:

\documentclass{article}
\usepackage{amsmath}
\usepackage{color}
\begin{document}
$A = \def\ba#1#2{a_{#1#2}} \def\ra{\color{red}\ba} \begin{bmatrix} \ra11 & \ra12 & \ra13 & \ba14 \\ \ra21 & \ra22 & \ra23 & \ba24 \\ \ra31 & \ra32 & \ra33 & \ba34 \end{bmatrix}$
\end{document}


## Update

You can declare a new column type including the color:

\documentclass[table]{article}
\usepackage{xcolor}
\usepackage{array}

\newcolumntype{E}{>{\color{red}}c}

\begin{document}

$\left[ \begin{array}{*{3}{E}c} 1 & 2 & 3 & 0 \\ 4 & 5 & 6 & 0 \\ 7 & 8 & 9 & 0 \end{array} \right]$

\end{document}


This can be done using collcell:

\documentclass[table]{article}
\usepackage{tikz}
\usepackage{collcell}

\newcommand\ColCell[1]{%
\pgfmathparse{#1>0?1:0}%
\ifnum\pgfmathresult=1\relax\color{red}\fi#1}

\newcolumntype{E}{>{\collectcell\ColCell}c<{\endcollectcell}}

\begin{document}

$\left[ \begin{array}{*{6}{E}} 1 & 2 & 3 & 4 & 0 \\ 5 & 0 & 7 & 8 & 0 \\ 1 & 2 & 0 & 4 & 0 \\ 5 & 6 & 7 & 8 & 0 \\ \end{array} \right]$

\end{document}


• Though the answer is pretty useful and I upvoted it, what I really need is how to draw at once the elements of that 3 x 3 block (the last zero column could be substituted by any other column with different elements). I guess a modification of that code should work, right? – thanasissdr Sep 9 '15 at 20:24
• @thanasissdr Your question didn't mentions this. doest it? The title is "Coloring elements of a block of a matrix" and the first line of the body is "Assume I have the matrix". I assumed you have the matrix and provided the answer. If you meant something different you should have stated that clearly from the beginning. – Gonzalo Medina Sep 9 '15 at 20:29
• I'm really sorry for that. I tried to edit the question. – thanasissdr Sep 9 '15 at 20:34
• Where does the question say that positive elements should be colored? – egreg Sep 9 '15 at 20:49
• @egreg Check the edit history. Original phrasing " I want to draw in red color the elements of the 3 x 3 block which are not zero". Since entries were non negative, I assumed not zero meant possitive. – Gonzalo Medina Sep 9 '15 at 21:05