Extract specific values from vector
Afficher commentaires plus anciens
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???
Réponses (2)
Andrei Bobrov
le 9 Oct 2012
Modifié(e) : Andrei Bobrov
le 11 Oct 2012
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 commentaire
Snake
le 9 Oct 2012
Snake
le 9 Oct 2012
0 votes
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!