How to efficiently find and step through similar values in a vector.
조회 수: 4 (최근 30일)
이전 댓글 표시
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
채택된 답변
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!