0

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.

fpe
  • 2,700
  • 2
  • 23
  • 47
  • @MitchWheat: it has to result into a `[1,N*(N+1)/2]` array, so only `N*(N+1)/2` entries. – fpe Jun 04 '13 at 14:13
  • 3
    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. –  Jun 04 '13 at 14:18
  • @woodchips: well, actually, at "second-hand" I had already thought about that approach, and probably I'll go with that in the end. – fpe Jun 04 '13 at 14:22

1 Answers1

0

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.

Community
  • 1
  • 1
shoelzer
  • 10,648
  • 2
  • 28
  • 49
  • We do this sort of thing all of the time in Matlab with vectorized calculations. In computer science the concept is known as the [`"space-time tradeoff"`](http://en.wikipedia.org/wiki/Space–time_tradeoff). If you need to get back a bit of memory at the cost of some performance (especially here where there's only about 50% sparsity), we have `sparse` matrices. – horchler Jun 04 '13 at 14:50