3

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.

4 Answers 4

7

What about

max_dist = max(x) - min(x) 

?

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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.

Comments

1

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.

1 Comment

That would calculate the maximum distance between succeeding elements. I'd rather like to have have it over all possible combinations.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.