# How to form a variable from matrix elements

I have matrix with n rows and 2 columns, say m = {{x11, y12}, {x21, y22}, ..., {xn1, yn2}.

Now, I want to form three new variables for example:

m = {{1, 2}, {0, 2}, {3, 2}, {0, 2}, {0, 2}, {0, 2}, {4, 2}}


where all elements in second column are 2.

First say variable v that will select elements form matrix m under these conditions:

if $x_{i,1} = 0$ then $1$ else $0$

Result in case of above example: v={0, 1, 0, 1, 1, 1, 0}. I construct it like that:

one[x_] := If[x == 0, 1, 0];
v=one /@ m[[All,1]]


Because v and all new other variables have only one column and n row I will drop down the index for column in next notation. For example: $v_{i} - v_{i-1}$ refers to the $v_{i,1} - v_{i-1,1}$; $-i$ refers to the $i^{th}$ row.

Second variable say vv had to be formed of elements by counting the run sequences of 1 from v:

if $v_{i} = 1$ then $vv_{i} = v_{i} + vv_{i-1}$ else $0$

Result in the case of the previous example: vv = {0, 1, 0, 1, 2, 3, 0}, with v = {0, 1, 0, 1, 1, 1, 0}.

In the end I want to form variable say f which is form from elements of first m matrix taking into account these rules (conditions):

if $vv_{i} > 1$ then $f_{i} = f_{i-1} * m_{i,2}$;

so if we take the $6^{th}$ row in previous example ((2*2)*2).

if $vv_{i} = 1$ then $f_{i} = m_{i,2}$;

so second row of $f_{2} = y22$

else $f_{i} = m_{i,1}$;

so first row of $f_{1} = x11$ or $1$

Final result should be:

f = {1, 2, 3, 2, 4, 8, 4)


The following gets the first two steps:

m = {{1, 2}, {0, 2}, {3, 2}, {0, 2}, {0, 2}, {0, 2}, {4, 2}};

v = 1 - Unitize[m[[All, 1]]]
(*{0,1,0,1,1,1,0} *)

vv = Flatten@(Accumulate /@ Split@v)
(* {0,1,0,1,2,3,0} *)


Update: ... the last step

ClearAll[ff];
ff = 1;
ff[n_] := Piecewise[{{ff[n-1] m[[n, 2]], vv[[n]] > 1}, {m[[n, 2]], vv[[n]] == 1}}, m[[n, 1]]];

ff /@ Range
(* {1, 2, 3, 2, 4, 8, 4} *)

• Thanks, can You help me to change Accumulate function in vv into multiply (vv(i)=vi x vv(i−1) Oct 30, 2014 at 12:43
• @Branimir, how do you initialize your f(i); i.e. what should f(1) be?
– kglr
Oct 30, 2014 at 17:52
• Any value, preferably 0. This value will be dropped from further analysis. Oct 30, 2014 at 18:14