TYL
TYL

Reputation: 1637

Extract blocks of certain number from array

I have a vector and I would like to extract all the 4's from it:

x = [1 1 1 4 4 5 5 4 6 1 2 4 4 4 9 8 4 4 4 4]

so that I will get 4 vectors or a cell containing the 4 blocks of 4's:

[4 4], [4], [4 4 4], [4 4 4 4]

Thanks!

Upvotes: 2

Views: 104

Answers (4)

Robert Seifert
Robert Seifert

Reputation: 25232

This should be pretty fast, using accumarray:

X = 4;

%// data
x = [1 1 1 4 4 5 5 4 6 1 2 4 4 4 9 8 4 4 4 4]

%// mask all 4
mask = x(:) == X

%// get subs for accumarray
subs = cumsum( diff( [0; mask] ) > 0 )

%// filter data and sort into cell array
out = accumarray( subs(mask), x(mask), [], @(y) {y} )

Upvotes: 2

rahnema1
rahnema1

Reputation: 15837

with regionprops we can set property PixelValues so the function returns 1s instead of 4s

x = [1 1 1 4 4 5 5 4 6 1 2 4 4 4 9 8 4 4 4 4]
{regionprops(x==4,'PixelValues').PixelValues}

if we set property PixelIdxList the function returns a cell of indices of 4s:

{regionprops(x==4,'PixelIdxList').PixelIdxList}

Update(without image processing toolbox): this way we can get number of elements of each connected components:

c = cumsum(x~=4)
h=hist(,c(1):c(end));
h(1)=h(1)+~c(1);
result = h(h~=1)-1

Upvotes: 1

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22225

You can create cells from the appropriate ranges using arrayfun:

x = [1 1 1 4 4 5 5 4 6 1 2 4 4 4 9 8 4 4 4 4];     
x = [0, x, 0]; D = diff (x==4);               % pad array and diff its mask
A = find (D == 1); B = find (D == -1);        % find inflection points
out = arrayfun (@ (a,b) {x(a+1 : b)}, A, B)   % collect ranges in cells

Upvotes: 3

Jeremy Kahan
Jeremy Kahan

Reputation: 3826

idx=find(x==4);
for (i= 1:length(idx)) 
   if (i==1 || idx(i-1)!=idx(i)-1)if(i!=1) printf(",") endif; printf("[") endif;
   printf("4");
   if (i<length(idx)&&idx(i+1)==idx(i)+1) printf(",") else printf("]") endif
endfor

Note this won't give the actual vectors, but it will give the output you wanted. The above is OCtave code. I am pretty sure changing endfor and endif to end would work in MAtlab, but without testing in matlab, I am not positive.[edited in light of comment]

Upvotes: 1

Related Questions