Extract specific values from vector
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (2)
Andrei Bobrov
am 9 Okt. 2012
Bearbeitet: Andrei Bobrov
am 11 Okt. 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));
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!