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,开发者_如何学JAVA 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.
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
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
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)
MapAt function accepts the following Part specification:
MapAt[f, mat, {All, 3}]
to apply 'f' to column 3 of your matrix.
Another compact solution I found is using Map and MapAt:
Here is an example Matrix:
mat={{3,4,5},{4,7,5},{2,6,7},{3,6,9}}
Now apply the function f to the second column:
n=2;
Map[MapAt[f,#,n]&,mat]
The result is then:
{{3,f[4],5},{4,f[7],5},{2,f[6],7},{3,f[6],9}}
精彩评论