# Width-dependent MatrixForm

When writing fractions, Mathematica has a quite intelligent behaviour: If the fraction gets too long to fit on the width of the notebook, it is automatically replaced by /.

However, by default nothing like this happens for matrices given in MatrixForm. Therefore my question is: Is it possible to write a DecayingMatrixForm which shows as MatrixForm if the matrix fits into the notebook's width, but switches to showing the list when the notebook is resized to be more narrow?

If that is not possible, is it at least possible to have that decision dependent on the current notebook width when first displaying the matrix?

Note that the solution should work correctly also if MatrixForm is used inside an expression, as in Table[MatrixForm[Table[f[i,j],{i,1,n},{j,1,n}]],{n,1,20}].

-
This is a very interesting question; I've never considered the mechanism by which that replacement is performed. –  Mr.Wizard Apr 26 '12 at 6:59
–  Alexey Popkov Apr 26 '12 at 9:14

ClearAll[DecayingMatrixForm];
Unprotect[$OutputForms]; AppendTo[$OutputForms, DecayingMatrixForm];
Protect[$OutputForms]; DecayingMatrixForm /: Format[DecayingMatrixForm[mat_?MatrixQ], StandardForm] := With[{m = Map[Defer, mat, {2}], mw=matrixWidth[mat]}, Dynamic[ If[First@CurrentValue["WindowSize"] > mw, MatrixForm[m], m]]]  Here's the raw matrixWidth function. It is very raw, feel free to edit and improve it if you like, or replace it by a cool built-in... fsize2pixels = Interpolation[{{6, 8}, {7, 9}, {7.5, 10}, {8, 11}, {9, 12}, {10, 13}, {10.5, 14}, {11, 15}, {12, 16}, {13, 17}, {13.5, 18}, {14, 19}, {14.5, 20}, {15, 21}, {16, 22}, {17, 23}, {18, 24}, {20, 26}, {22, 29}, {24, 32}, {26, 35}, {27, 36}, {28, 37}, {29, 38}, {30, 40}, {32, 42}, {34, 45}, {36, 48}}] matrixWidth[mat_?MatrixQ] := CurrentValue["Magnification"] With[{w = Length@First@mat, chars = Max[ StringLength /@ StringJoin /@ Map[ToString, mat, {2}]]}, 116 + 0.5 fsize2pixels[CurrentValue["FontSize"]] (chars + w + 1)]  - Where did you find out about $OutputForms it doesn't show up in the documentation? –  rcollyer Apr 26 '12 at 14:19
Nice. However, the Dynamic also causes the matrix to track all future assignments; e.g. for DecayingMatrixForm[Table[f[i,j],{i,1,10},{j,1,10}]] on subsequent defining f[1,1]=3 the displayed value for the first matrix element also changes to 3. Maybe wrapping the individual matrix elements in HoldForm would help. –  celtschk Apr 26 '12 at 14:25
@rcollyer, I guess it was about a month ago when I was investigating the forms. I came into $BoxForms, because of an error message, and then intuitively tried Names["$*Forms"] to get a very interesting result –  Rojo Apr 26 '12 at 14:42
$OutputForms contains $PrintForms which contain $BoxForms. $OutputForms has all those forms that output with the //*Form CellLabel. $PrintForms all those that work with ToString, and $BoxForms the input box forms that you can add to MakeBoxes, etc –  Rojo Apr 26 '12 at 14:44