Applying a function to every item in a column of a matrix
The easiest way to apply different functions to different columns is with Query
. This has the added advantage that columns you don't want to do anything with do not have to be specified explicitly. For example, to apply functions to the 1st and 3rd columns:
Query[All, {1 -> f, 3 -> g}] @ RandomInteger[10, {5, 4}] // TableForm
This also works very well with data in the form of a list of associations.
You can define a pure function func1
with the desired transformation of various Part
s of an input n-tuple and use it with Map
:
func1 = {#[[1]], #[[2]] + 1, Sqrt @ #[[3]], Quantity[#[[4]], "Meters"], #[[5]], #[[6]]} &;
Map[func] @ test
or define your function using Slot
s and use it with Apply
:
func2 = {#, #2 + 1, Sqrt @ #3, Quantity[#4, "Meters"], #5, #6} &;
func2 @@@ test
to get
One way of applying a function to a specific column of a matrix is to use Inner
(which may be thought of as a generalized form of Dot
). (see also here)
Inner[Times,test,ConstantArray[1,Length@test[[1]]],{#1,f@#2,##3}&]//TeXForm
$$ \left( \begin{array}{cccccc} 0 & f[1] & 2 & 3 & 4 & 5 \\ 1 & f[2] & 3 & 4 & 5 & 6 \\ 2 & f[3] & 4 & 5 & 6 & 7 \\ 3 & f[4] & 5 & 6 & 7 & 8 \\ 4 & f[5] & 6 & 7 & 8 & 9 \\ 5 & f[6] & 7 & 8 & 9 & 10 \\ 6 & f[7] & 8 & 9 & 10 & 11 \\ 7 & f[8] & 9 & 10 & 11 & 12 \\ 8 & f[9] & 10 & 11 & 12 & 13 \\ 9 & f[10] & 11 & 12 & 13 & 14 \\ 10 & f[11] & 12 & 13 & 14 & 15 \\ \end{array} \right) $$
For the requested modifications:
Inner[Times,test,ConstantArray[1,Length@test[[1]]],
{#1,#2+1, Sqrt@#3, Quantity[#4, "meters"],##5}&
]//TeXForm
$$ \left( \begin{array}{cccccc} 0 & 2 & \sqrt{2} & 3\text{m} & 4 & 5 \\ 1 & 3 & \sqrt{3} & 4\text{m} & 5 & 6 \\ 2 & 4 & 2 & 5\text{m} & 6 & 7 \\ 3 & 5 & \sqrt{5} & 6\text{m} & 7 & 8 \\ 4 & 6 & \sqrt{6} & 7\text{m} & 8 & 9 \\ 5 & 7 & \sqrt{7} & 8\text{m} & 9 & 10 \\ 6 & 8 & 2 \sqrt{2} & 9\text{m} & 10 & 11 \\ 7 & 9 & 3 & 10\text{m} & 11 & 12 \\ 8 & 10 & \sqrt{10} & 11\text{m} & 12 & 13 \\ 9 & 11 & \sqrt{11} & 12\text{m} & 13 & 14 \\ 10 & 12 & 2 \sqrt{3} & 13\text{m} & 14 & 15 \\ \end{array} \right) $$
If all that is required is to multiply each value in a column by a factor, then Dot
is sufficient (and very fast).
For example, to multiply all values in column-2 by 100:
test.DiagonalMatrix[{1,100,1,1,1,1}]//TeXForm
$$\left( \begin{array}{cccccc} 0 & 100 & 2 & 3 & 4 & 5 \\ 1 & 200 & 3 & 4 & 5 & 6 \\ 2 & 300 & 4 & 5 & 6 & 7 \\ 3 & 400 & 5 & 6 & 7 & 8 \\ 4 & 500 & 6 & 7 & 8 & 9 \\ 5 & 600 & 7 & 8 & 9 & 10 \\ 6 & 700 & 8 & 9 & 10 & 11 \\ 7 & 800 & 9 & 10 & 11 & 12 \\ 8 & 900 & 10 & 11 & 12 & 13 \\ 9 & 1000 & 11 & 12 & 13 & 14 \\ 10 & 1100 & 12 & 13 & 14 & 15 \\ \end{array} \right) $$
test = Table[{x, x + 1, x + 2, x + 3, x + 4, x + 5}, {x, 0, 10}];
Comparison with the very neat method given by Sjoerd Smit
(Query[All, {2 -> (#+1&),3->Sqrt,4 ->(Quantity[#, "meters"]&)}]@test)===
Inner[Times,test,{1,1,1,1,1,1},{#1,#2+1,Sqrt@#3, Quantity[#4, "meters"],##5}&]
True