# How to decorate data in a matrix for reporting purposes?

I want to create a report from two matrices m1 and m2 (already created, and available) with data.

The report should (roughly) look like the output of the following code:

ClearAll[sa];
sa = SparseArray[Table["", 5, 5]];
sa[[1, 1]] = "0\n1" ;
sa[[2, 1]] = "1\n25";
sa[[3, 1]] = "2\n4";
sa[[3, 2]] = "11\n30";
sa[[4, 1]] = "3\n2";
sa[[4, 2]] = "21\n15";
sa[[4, 3]] = "111\n5";
sa[[5, 1]] = "4\n2";
sa[[5, 2]] = "31\n5";
sa[[5, 3]] = "22\n2";
sa[[5, 4]] = "211\n3";
sa[[5, 5]] = "1111\n0";
sa // MatrixForm


The data before the newline ( \n ) comes from the first matrix m1, the data after the newline comes from the second matrix m1.

In fact m1 contains textual headings for the data in m2.

My question is in fact, given a matrix containing only data like, for example:

ClearAll[sa];
sa = SparseArray[Table["", 5, 5]];
sa[[1, 1]] = 1 ;
sa[[2, 1]] = 25;
sa[[3, 1]] = 4;
sa[[3, 2]] = 30;
sa[[4, 1]] = 2;
sa[[4, 2]] = 15;
sa[[4, 3]] = 5;
sa[[5, 1]] = 2;
sa[[5, 2]] = 5;
sa[[5, 3]] = 2;
sa[[5, 4]] = 3;
sa[[5, 5]] = 0;
sa // MatrixForm


Then, what is the best strategy to decorate the cell elements with all sorts of textual attributes, color, etc., and in my case a textual heading?

Note that the data and the data for the cell heading texts are initially stored in two matrices and that I am best helped with a general strategy to decorate data in a matrix for reporting purposes.

Finally, what is the best function to produce the report?

• Take a look at Grid Commented Jun 17, 2019 at 17:31
• Thanks, but I have looked at Grid, but alas doesn't answer all my questions. Commented Jun 17, 2019 at 17:35
• Have you looked at all of the Options of Grid? What functionality do you need that is missing? Commented Jun 17, 2019 at 18:24
• Yes, I use it often. If only there was something like ItemHeading. Commented Jun 18, 2019 at 6:31

I changed sa = SparseArray[Table["", 5, 5]]; to sa = ConstantArray["", {5, 5}, SparseArray]; in the second code block.

decorate = ToString[Style[#, Italic, Bold, RandomColor[],
RandomInteger[{14,24}]], StandardForm]&;

itemheadings = {0, 1, 2, 11, 3, 21, 111, 4, 31, 22, 211, 1111};

nzp = sa["NonzeroPositions"];
nzv = sa["NonzeroValues"];
newvalues = StringRiffle[#, "\n"] & /@ Transpose[{styledheadings, ToString /@ nzv}];

report = SparseArray[nzp -> newvalues, {5, 5}, ""];
report  // MatrixForm


Alternatively, let

m2 = SparseArray[nzp -> styledheadings, Automatic,""];


define newvalues as

newvalues = StringRiffle[#, "\n"] & /@ Transpose[{m2["NonzeroValues"], ToString /@ nzv}];


We can also Riffle two matrices and use Grid:

m1 = sa;
m2 = SparseArray[nzp -> itemheadings, Automatic, ""];
styledm2 = Map[decorate, m2, {-1}];
Grid[Riffle[styledm2, m1], Dividers -> {False, {{True, False}}}]


• Thank you very much, this helps a lot. Commented Jun 18, 2019 at 18:37
• @nilo, my pleasure. Thank you for the accept.
– kglr
Commented Jun 18, 2019 at 19:10