# Lexicographically order matrix into a vector

I am trying to implement the algorithm contained in this article here. It is about solving a 2 and 2.5D Fredholm integral, focused on bidimensional NMR experiments. I've made significant progress, despite this being my very first time doing any computational science. The output I get is clearly wrong, but seems shifted from what would be ideal. I am trying to stamp out problematic areas, and am wondering if I interpreted this passage wrong:

In principle, the 2-D problem in (2) can be reduced to a 1-D problem $$m_r = K_0f_r + \epsilon_r \quad r=1,...,R$$. Here, the vectors $$m_r$$, $$f_r$$ and $$e_r$$ are obtained by lexicographically ordering matrices $$M_r$$, $$F_r$$, $$E_r$$.

For reference, eq (2) that they mention is the Fredholm integral we are trying to solve, which relates the measured data $$M_r$$ and the joint probability distribution $$\mathcal{F}_r$$ of the relaxation times (x, y):

$$M_r(\tau_1,\tau_2) = \int \int k_1(x, \tau_1)k_2(y, \tau_2)\mathcal{F}_r(x,y)dxdy + \epsilon_r(\tau_1,\tau_2) \quad r=1,...,R$$

According to the text, the shape of $$M_r$$ is $$N_1\times N_2$$ and $$m_r$$ is $$(N_1N_2\times 1)$$. I thought I could use a simple reshape, but looking at definitions of lexicographic, there seems to be a sort involved. So, which one of these two python snippets is right? Or is it something else entirely?

• m_r = np.sort(M_r, axis=None)[:, np.newaxis] or
• m_r = M_r.reshape((N1*N2, 1))?

Later, they also state that

The matrix $$F_r$$ is estimated by reordering $$f_r$$ into the matrix notation.

So, I could do a simple reshape back. But if I have to unsort $$F_r$$, which has the shape $$N_x \times N_y$$, I am lost.

• Instead of np.sort try np.lexsort. – Alone Programmer Mar 20 '20 at 20:38
• I don't think that's right. For example, say a = np.array([[1,2,3],[4,5,6]]). np.lexsort(a) returns [1,2,3], which has the wrong shape in my example. And besides, how would I unsort $F_r$ if I used lexsort on M_r? – K.Cl Mar 20 '20 at 20:47
• I don't believe that the authors actually mean lexicographic- it appears that they simply used the wrong word to describe this very common process. – Brian Borchers Mar 21 '20 at 4:54
• @BrianBorchers so, it's a reshape? – K.Cl Mar 21 '20 at 10:49
• The sort is lexographic to order the points in the domain, by (x,y) point coordinates. If you call lexsort on the vector, it will sort the values of those points instead. You can get the correct order by lexsorting the $(N_1N_2) \times 2$ tall matrix of point coordinates. If the points are arranged in a regular grid this is equivalent to a reshape – Nick Alger Mar 22 '20 at 4:19