We have a nested matrix as:

nested={{he, {{e, f, g, h}, {s, 0, q, i}, {s, 0, q, j}}}, {ho, {{e, f, g, 
  h}, {0, u, t, i}, {u, t, 0, j}}}}

and with the line MapAt[MatrixForm, nested, {{All, All}, {}}] the matrix form can be shown:

enter image description here

The desire situation can be achieved when some elements such as "he" and "ho" written in the background of Blue (color) and in the right sub_matrices, the elements in the top rows ("e, f, g, h") and the most right columns ("h,i,j") can be written in the background of Darker[ Yellow, 0.01]. However I know Grid can help for matrices or tables but I don't know how I can access to the desire situation for a nested matrix with help of Grid or something else?


2 Answers 2

mfnested = MapAt[MatrixForm, nested, {{}, {;; , ;;}}];
colF = MapAt[Function[{i}, Item[i, Background -> #2[[1]]]], #, #2[[2]]] &;

Fold[colF, mfnested, 
  {{Yellow, {{1, All, 2, 1, 1, All}, {1, All, 2, 1, All, -1}}}, 
   {Lighter@Blue, {{All, All, 1}}}}]

Mathematica graphics

Grid[MapAt[Grid[#, Background -> {{-1 -> Yellow}, {1 -> Yellow}}] &, 
           nested, {{All, 2}}], Background -> {{Lighter@Blue}, None}, 
     Frame -> All]

Mathematica graphics


MapIndexed can be used to apply styling to elements conditionally based upon the their indices within the matrix. For example:

format[v_, {_, 1}] := framed[v, White, Blue]
format[v_, {_, 2}] := MatrixForm[v, TableSpacing -> {None, None}]
format[v_, {_, 2, 1, _} | {_, 2, _, 4}] := framed[v, Black, Darker[Yellow, 0.01]]
format[v_, _] := v

framed[v_, f_, b_] := Framed[Style[v, f], Background -> b, FrameStyle -> None]

MapIndexed[format, nested, -1] // MatrixForm

screenshot showing formatted matrix

The helper function format defines the rules for each element of the matrix based upon its index. For example, the index pattern {_, 1} matches the elements in the first column of the main matrix, and the index pattern {_, 2, _, 4} matches the fourth column of the each submatrix in the second column of the main matrix.

The helper function framed provides a shorthand for a frame with no border and specified foreground and background colours.

Finally, the MapIndexed expression is used to apply format to every element at all levels in the matrix (down to level bottom-most level, -1).


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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