0
votes

I hope you will have the right answer to this question, which is rather challanging.

I have two uni-dimensional vectors Y and Z, which hold the coordinates of N grid points located on a square grid. So

Ny points along Y
Nz points along Z
N = Ny*Nz
Y = Y[N]; (Y holds N entries)
Z = Z[N]; (Z holds N entries)

Now, the goal would be generating the distance matrix D, which holds N*N entries: so each row of matrix D is defined as the distance between the i-th point on the grid and the remnant (N - i) points.

Generally, to compute the whole matrix I would call

D = squareform(pdist([Y Z]));

or,equivalently,

D = pdist2([Y Z],[Y Z]).

But, since D is a symmetric matrix, I'd like to generate only the N(N + 1)/2 independent entries and store them into a row-ordered vector Dd.

So the question is: how to generate a row-ordered array Dd whose entries are defined by the lower triangular terms of matrix D? I'd, furthermore, like storing the entries in a column-major order.

I hope the explanation is clear enough.

1
@MitchWheat: it has to result into a [1,N*(N+1)/2] array, so only N*(N+1)/2 entries.fpe
Far simpler (and far faster) to generate the entire matrix, then toss those you don't wish to keep. This is a phantasm, that it could be simpler in MATLAB if you only generate the upper triangle. Unless the amount of memory blows your budget, don't bother with the false optimization.user85109
@woodchips: well, actually, at "second-hand" I had already thought about that approach, and probably I'll go with that in the end.fpe

1 Answers

0
votes

As woodchips commented, it is simpler and faster to compute the whole matrix and extract the elements you care about. Here's a way to do it:

ndx = find(tril(true(size(D))));
Dd = D(ndx);

If you absolutely must compute elements of Dd without computing matrix D first, you probably need a double for loop.