Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format two separate lists in columns, rather than rows in Mathematica?

This seems like it should be a piece of cake, but I haven't found the answer in Mathematica's documentation. Say I have two separate lists, for example x={1,2,3,4,5} and y={1,4,9,16,25}. I want to format these lists as a table with each list as a column, like this:

x  y  
1  1  
2  4  
3  9  
4 16  
5 25  

But if I do TableForm[x,y], I get only the first column, like this:

1  
2  
3  
4  
5  

If I do Grid[{x,y}], I get a table, but formatted as rows instead of columns, like this:

1 2 3  4  5  
1 4 9 16 25   

Now, if I have my values as {x,y} pairs, rather than separate lists, then I can get almost what I want,like so:

Input: Table[{n,n^2},{n,1,5}]//TableForm

Output:   
1 1  
2 4  
3 9  
4 16  
5 25  

I say almost, because I'd like to have the variable names at the top of each column, and I'd like the columns justified so that the ones digits are always placed vertically in the "ones place", the tens digits in the "tens place", etc.

So, back to my question: If I have two separate lists of the same length, how can I format them as a table of columns? I checked the MMA documentation for Grid and TableForm, but I couldn't find a way to do it. Did I miss something? If there's no direct way to do it, is there a way to transform two separate lists into pairs of values that could then be formatted in columns using TableForm?

Thanks for any suggestions you might have.

like image 773
eipi10 Avatar asked Feb 11 '11 13:02

eipi10


1 Answers

Personally I prefer Grid to TableForm. Maybe something like this?

Some preliminaries:

x = {1, 2, 3, 4, 5};
y = {1, 4, 9, 16, 25};
grid = Transpose@{x, y};
headings = {{Item["x", Frame -> {True, True}], 
    Item["y", Frame -> {True, False}]}};

The following code,

Grid[Join[headings, grid], Alignment -> Right, Dividers -> All, 
 Spacings -> {3, 1}, FrameStyle -> Orange]

gives this as output, for example:

enter image description here

like image 72
681234 Avatar answered Nov 10 '22 06:11

681234