Mathematica: How to apply function to a certain column of a table

janitor048 picture janitor048 · Dec 31, 2010 · Viewed 11.7k times · Source

I would like to apply a function to a specific column of a table. Say to the i-th column of a (m x n) table. Actually I just want to multiply all elements in that column with a scalar, but the application of a general function would be fine as well.

It probably just needs some Map or MapAt command, maybe combined with a Transpose in order to apply to rows instead of columns - but I can't figure out the correct syntax for addressing an entire column (or row)..

Any hints would be highly appreciated.

Answer

Bill White picture Bill White · Dec 31, 2010

Here's a 3x3 table:

In[1]:= table = {{1,2,3}, {4,5,6}, {7,8,9}}
Out[1]= {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
In[2]:= table//TableForm
Out[2]//TableForm= 1   2   3
                   4   5   6
                   7   8   9
Column 2 is table[[All, 2]]:

In[3]:= table[[All, 2]]
Out[3]= {2, 5, 8}

So it's a simple matter to modify only that column:

In[4]:= table[[All, 2]] = 10 * table[[All, 2]]
Out[4]= {20, 50, 80}
In[5]:= table//TableForm
Out[5]//TableForm= 1   20   3
                   4   50   6
                   7   80   9