Extract specific values from vector
1 次查看(过去 30 天)
显示 更早的评论
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???
0 个评论
回答(2 个)
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));
另请参阅
类别
在 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!