How to efficiently find and step through similar values in a vector.
4 views (last 30 days)
Show older comments
For a vector, such as:
X = [5 5 5 2 2 ..]
Is there a native, no toolbox, elegant way to identify the length of contiguous 'regions', eg
len = [3 2 ...]
And efficiently group their indices, eg
ind = {[1 2 3] [4 5] ...}
My use case is to quickly step through a large number of regions in a loop.
In my example i have a fast but ugly solution that only works if X is sorted.
n = 1e5; %vector length
X = sort(round(rand(n,1)*n)); %sorted values
tic
[U,~,J] = unique(X); %find similar 'regions' in a vector
for k = 1:numel(U) %step through regions
I = find(k==J)'; %find index of region elements (SLOW!)
%do stuff
end
toc %~10sec
tic
ind = group_contiguous_values(X); %find index of contiguous regions, X must be sorted
for k = 1:numel(ind)
I = ind{k};
%do stuff
end
toc %~100x times faster, time scales linearly with n
function ind = group_contiguous_values(X)
%Group contiguous values and list their indices (only works if X is sorted)
assert(issorted(X),'X must be sorted')
[~,~,J] = unique(X);
len = diff([0;find(diff([J(:);-1])~=0)]); %find length of each 'region', eg x=[5 5 5 2 2 ..] > len=[3 2 ..]
ind = mat2cell(1:numel(J),1,len); %indecies for each region, eg ind={[1 2 3] [4 5] ..}
end
0 Comments
Accepted Answer
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!