# How to apply multiple format to a list

I have a nested list like

matrix = {{1.2345664, 2.38673956, 3.567846}, {0.00034554, 124.4554654,
6.34543}, {0.0000233, 244.34454, 2}}


and I want to apply MatrixForm, but also NumberForm[,{5,4}], because I want that in every element of the matrix the numbers are properly padded.

Is this possible in some way?

Interestingly perhaps, I want eventually write the resulting output list in a file.

P.S.: Now I write with Export["my_file.dat",Flatten[matrix]], and after I obtain the proper padding using a C program. But there must be a clever way...

-
Are you going to manipulate the matrix further ? MatrixForm[Table[NumberForm[matrix[[i, j]], {5, 4}] , {i, 3}, {j, 3}]] will do what you want but then you cannot, for instance, take Det or Inverse. –  b.gatessucks Mar 25 '13 at 18:49
@b.gatessucks No, I don't want to manipulate further the matrix, but I have problems in writing in a file if I don't use Export (I want to write in append mode so I'm using PutAppend). –  Fabrizio Mar 25 '13 at 22:21

You can do this a couple of different ways. This is easiest:

NumberForm[MatrixForm @ matrix, {5, 4}]


This works because NumberForm affects sub-expressions including ones wrapped in MatrixForm. You can do it the other way but it's more complicated:

Map[NumberForm[#, {5, 4}] &, matrix, {2}] // MatrixForm


You mention that you eventually want to export this. You should not need (or use) MatrixForm for export. The question of export of NumberForm formatted numbers may be answered here: How can I control the number format of exported data? In version 7 however the Accepted answer does not work. You might use something like:

Export[
"myfile.dat"
Map[ToString @ NumberForm[#, {5, 4}] &, matrix, {2}],
"Table"
]

-
I want to write in append mode, so I'm using PutAppend for writing, but in this case your solution doesn't work. Why? –  Fabrizio Mar 25 '13 at 22:17
@Fabrizio Could you be more specific? Ideally, post the code that isn't working, and the expected output. –  Mr.Wizard Mar 26 '13 at 0:23
The code is simply PutAppend[NumberForm[MatrixForm@matrix, {5, 4}], outFile], and the required output is the usual. –  Fabrizio Mar 26 '13 at 8:49
@Fabrizio Sorry, I didn't see your comment until today. It may be best to use WriteString as Put is better suited to writing expressions rather than formatted output. For example: str = OpenWrite["numform.dat"]; WriteString[str, NumberForm[Grid @ matrix, {5, 4}]]; Close[str]; -- does that help? –  Mr.Wizard Mar 30 '13 at 23:33
Yes, thanks. Also I have now learned that is better convert expressions in strings before writing them in a file. –  Fabrizio Mar 31 '13 at 10:21