# Divide the elements of one column with the corr element of another column

I have an $N\times 2$ matrix $A = \begin{pmatrix} a_{11} & a_{12} \\ a_{21} & a_{22} \\ \vdots & \vdots \\ a_{N1} & a_{N2} \end{pmatrix}$. What is the cleanest code to make a new $N\times 2$ matrix $B$ with the first column unchanged but second column should consist of elements of second column of $A$ divided by the corresponding element of the first column of $A$. That is $a_{1i}$ divide by $a_{i1}$.

Thus the elements of $B$ should read

$B=\begin{pmatrix} a_{11} & a_{12}/a_{11} \\ a_{21} & a_{22}/a_{21} \\ \vdots & \vdots \\ a_{N1} & a_{N2}/a_{N1} \end{pmatrix}$

• What about b = {#1, #2/#1} & @@@ a, clean enough? Sep 30 '16 at 15:32
• Woah. That's an answer. Sep 30 '16 at 15:35

(*matlab-like approach*)

nRows = 5;
nCols = 2;
(mat = Table[i + j, {i, nRows}, {j, nCols}]) // MatrixForm


mat[[All, 2]] = mat[[All, 2]]/mat[[All, 1]];
mat // MatrixForm


• +1 Also: mat[[All, 2]] /= mat[[All, 1]] Sep 30 '16 at 18:40

It's always nice to have a clean method, but if you have large matrix, performance can be an issue. Consider following comparison:

a = RandomReal[1, {1000000, 2}];
{t1, r1} = AbsoluteTiming[{#1, #2/#1} & @@@ a];
{t2, r2} = AbsoluteTiming[Transpose@{#1, #2/#1} & @@ Transpose@a];
{t1, t2, r1 == r2}
(* {1.48458, 0.024882, True} *)


The first solution iterates over large index, it makes it way slower, although a little bit more cleaner visually.

• Good demonstration! Sep 30 '16 at 16:19