How to efficiently find and step through similar values in a vector.
6 次查看(过去 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!