How to find a general math formula of a vector and its matrix?

I have a vector x of size 1xM*N for some M and N. I convert this vector to a matrix X with M rows and N columns. I would like to find a relation between the indices of the vector x and the elements of the matrix X.

Here is an example for M=3 and N=3:

x = [x_11 x_12 x_13 x_21 x_22 x_23 x_31 x_32 x_33]

X = [ x_11 x_12 x_13
x_21 x_22 x_23
x_31 x_32 x_33 ]

Now let say I want to get x(4). I know that x(4) = x_21 = X(2, 1).

How to get indices 2 and 1 from 4 or vice versa ?

I tried the following:

let say we want to find $x(i)$, then $X(m,n)=x(i)$ where $m$ and $n$ are given by: $$m = floor((i + M- 1)/(M))$$ and $$n = i + M - m * M$$ but I think there is a mistake.

Since you have vectorized by rows, $$i=(m-1)\cdot N+n$$

For your example, $m=2$ and $n=1$, so $i=(2-1)\cdot3+1=3+1=4$.

In reverse, $$n\equiv i\pmod{N}$$ $$m=\left\lfloor\frac{i-1}{N}\right\rfloor+1$$

Again, with your example $i=4$, so $m=\lfloor 4/3+1\rfloor=2$ and $n=1$.

Most programming languages will have $\mathrm{mod}(N,N)=0$, so you will probably want to use $\mathrm{mod}(i-1,N)+1$ to fix the error that would occur by using one-based indexing.

To write it without mod, $$n=i-N\cdot(m-1)$$

So, the equations you had were correct if you replace $M$ with $N$.

• Very nice. Thanks :) Aug 28 '14 at 14:03

In term of programming, I can get $m$ and $n$ from $i$ as follow:

for c = 1:M
v = (c-1)*N+1:c*N;
% v = [(c-1)*N+1, c*N].
[a, b] = ismember(i, v);
% a is a logical number indicates either i is in the vector v or not.
% b is the index where i is found.
if (a)
m = c;
n = b;
end
end