3
$\begingroup$

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}$

$\endgroup$
2
  • 4
    $\begingroup$ What about b = {#1, #2/#1} & @@@ a, clean enough? $\endgroup$
    – BlacKow
    Sep 30 '16 at 15:32
  • $\begingroup$ Woah. That's an answer. $\endgroup$ Sep 30 '16 at 15:35
9
$\begingroup$
(*matlab-like approach*)

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

Mathematica graphics

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

Mathematica graphics

$\endgroup$
1
  • $\begingroup$ +1 Also: mat[[All, 2]] /= mat[[All, 1]] $\endgroup$
    – WReach
    Sep 30 '16 at 18:40
8
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ Good demonstration! $\endgroup$ Sep 30 '16 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.