MATLAB: How to find all elements within a certain range of each other

matrix manipulation

Suppose I have a vector A = [1 4 7 10 2 8] (in reality it is much longer). I want to find the indices of the elements which are within specific range of another element. So let's say my range = 1, it needs to return ans = [1 0 1 0 1 1] as 1 & 2 fit and 7 & 8. How do I do this effectively? I'd rather not use for loops.
thanks!

Best Answer

Interesting problem. How about:
[sortedA, indices] = sort(A);
inrange = find(diff(sortedA) <= range);
inrangeAidx = unique([indices(inrange) indices(inrange+1)]);
isinrange = zeros(size(A)); isinrange(inrangeAidx) = 1;