Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 824
janitor048 Avatar asked Dec 31 '10 14:12

janitor048


4 Answers

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
like image 80
Bill White Avatar answered Sep 19 '22 11:09

Bill White


For example,

ranfunc=Function[{f,mat, n},Transpose[MapAt[f /@ # &, Transpose[mat], n]]]

will apply f to each element of the nth column of mat. So, for instance,

ranfunc[Sin[Cos[#]] &, {{1, 2, 3}, {a, b, c}, {\[Alpha], \[Beta], \[Gamma]}}, 2]

will apply Sin[Cos[#]]& to each element of the second column, while

ranfunc[s*# &, {{1, 2, 3}, {a, b, c}, {\[Alpha], \[Beta], \[Gamma]}},2]

will multiply each element on the second column by s

like image 37
acl Avatar answered Sep 18 '22 11:09

acl


One versatile approach is to use ReplacePart

For example, to apply f to column 3 of mat:

(mat = Array[Subscript[a, ##] &, {4, 4}]) // MatrixForm

(newmat = ReplacePart[#, 3 -> f  @#[[3]] ] & /@ mat) // MatrixForm

The following multiplies each entry by 10:

(newmat2 = ReplacePart[#, 3 -> 10 #[[3]] ] & /@ mat) // MatrixForm

However, a 'quick' way to do this it as follows:

mat[[All, 3 ]] *= 10

(Unlike the first method, all entries in column 3 of mat are now modified. It is not clear whether you want to modify the existing table, or to create a new table with modifications, leaving the original intact)

like image 35
681234 Avatar answered Sep 20 '22 11:09

681234


MapAt function accepts the following Part specification:

MapAt[f, mat, {All, 3}]

to apply 'f' to column 3 of your matrix.

like image 30
icab Avatar answered Sep 21 '22 11:09

icab