Extract specific values from vector

15 ビュー (過去 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 Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by