Question

Let's assume that we have a vector like

x = -1:0.05:1;
ids = randperm(length(x));
x = x(ids(1:20));

I would like to calculate the maximum distance between the elements of x in some idiomatic way. It would be easy to just iterate over all possible combinations of x's elements but I feel like there could be a way to do it with MATLAB's built-in functions in some crazy but idiomatic way.

Was it helpful?

Solution

What about

max_dist = max(x) - min(x)

?

OTHER TIPS

Do you mean the difference between the largest and smallest elements in your vector ? If you do, then something like this will work:

max(x) - min(x)

If you don't, then I've misunderstood the question.

This is an interpoint distance computation, although a simple one, since you are working in one dimension. Really that point which falls at a maximum distance in one dimension is always one of two possible points. So all you need do is grab the minimum value and the maximum value from the list, and see which is farther away from the point in question. So assuming that the numbers in x are real numbers, this will work:

xmin = min(x);
xmax = max(x);
maxdistance = max(x - xmin,xmax - x);

As an alternative, some time ago I put a general interpoint distance computation tool up on the file exchange (IPDM). It is smart enough to special case simple problems like the 1-d farthest point problem. This call would do it for you:

D = ipdm(x,'subset','farthest','result','struct');

Of course, it will not be as efficient as the simple code I wrote above, since it is a fully general tool.

Uhh... would love to have a MATLAB at my hands and its still early in the morning, but what about something like:

max_dist = max(x(2:end) - x(1:end-1));

I don't know if this is what You are looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top