Extract specific values from vector

조회 수: 11 (최근 30일)
Snake
Snake 2012년 10월 9일
I have a vector which contains zeros and ones like that:
0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0.
Multiple ones after multiples zeros. I want to store only the ones. Plus the 8 zeros before the ones. The size of the vector is something like 120.000x1. The most of the element is zero. In which way it is possible to locate a series of ones, and store both the 8 last zeros followed by the located series of ones???

답변 (2개)

Andrei Bobrov
Andrei Bobrov 2012년 10월 9일
편집: Andrei Bobrov 2012년 10월 11일
a=[0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0];
idx = find([true,diff(a)~=0]);
nn = diff(idx);
out = cell2mat(arrayfun(@(x)[ones(1,x) zeros(1,8)],nn(find(a(idx)==1)),'un',0));
in response to a Snake remark
1. variant solution with use Image Processing Toolbox:
sstc = regionprops(a>0,'PixelIdxList');
idx = {sstc(:).PixelIdxList}; % indexs of ones
out = cell2mat(cellfun(@(ii)a([ii;ii(end) + (0:8)']),idx,'un',0));
2. Variant without use Image Processing Toolbox:
i0 = find([true;diff(a(:))~=0]);
ii = zeros(numel(a),1);
ii(i0(a(i0)>0)) = 1;
subs0 = cumsum(ii).*a(:);
val = (1:numel(a))'
idx = accumarray(subs0(subs0>0),val(subs0>0),[],@(x){x});
out = cellfun(@(i1)a([i1;i1(end)+(0:8)']),idx,'un',0);
out = cat(2,out{:});
or
i0 = find([true;diff(a(:))~=0]);
idx = cellfun(@(ii)ii(1):ii(2)-1,...
num2cell(i0(bsxfun(@plus,find(a(i0)),(0:1)')),1),'un',0);
out = cell2mat(cellfun(@(ii)a([ii;ii(end) + (0:8)']),idx,'un',0));
  댓글 수: 1
Snake
Snake 2012년 10월 9일
Thanks, clean and easy solution!!

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


Snake
Snake 2012년 10월 9일
Thank you, i ve qot another query, how can i store the indexes of the returned elements???

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by