필터 지우기
필터 지우기

Detect parts of a 0/1 (binary) vector consisting of only 0 or 1

조회 수: 1 (최근 30일)
Ilya
Ilya 2014년 4월 3일
편집: Ilya 2014년 4월 6일
Let's say I have a vector of 0 and 1:
a=[1 1 1 0 0 0 1 0 1 0 0 1 1 0];
It's needed to find a way to extract the vector's indices so that each group of extracted indices contains a part of a vector consisting of only zeros or only ones. For the given example it should be like:
[1 3] [4 6] [7] [8] [9] [10 11] [12 13] [14]
I thought about diff(), but some post-processing is definitely required after it...

채택된 답변

Sean de Wolski
Sean de Wolski 2014년 4월 3일
idx = find(diff([~a(1) a]))';
pcs = spdiags(rot90([idx-1 idx]));
pcs(end) = numel(a)
  댓글 수: 3
Image Analyst
Image Analyst 2014년 4월 3일
Wow - never would have guessed that.
Ilya
Ilya 2014년 4월 6일
편집: Ilya 2014년 4월 6일
A more robust solution (the same idea):
idx1 = find(diff([~a(1) a]));
idx2 = circshift(idx1-1,[0 -1]);
idx2(end) = numel(a);
pcs = [idx1; idx2];
The initial one may be wrong i.e. in case a=[1 1 1 1 0], due to the unpredictable spdiags() behavior.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2014년 4월 3일
If you have the Image Processing Toolbox, the 1's are given by the PixelIdxList property. You can do it in one line with a call to regionprops:
a=[1 1 1 0 0 0 1 0 1 0 0 1 1 0];
% Find 1's.
locations = regionprops(logical(a), 'PixelIdxList');
% Print out to command line:
for k = 1 : length(locations)
locations(k).PixelIdxList
end
% Find 0's.
locations = regionprops(logical(~a), 'PixelIdxList');
% Print out to command line:
for k = 1 : length(locations)
locations(k).PixelIdxList
end

카테고리

Help CenterFile Exchange에서 Image Processing Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by