0
votes

Consider an index vector consisting of ones and zeros:

I=[0 0 1 0 1 1 0 0 0];

How can I easily generate the following matrix in matlab:

J=[0 2;
  1 1;
  0 1;
  1 2;
  0 3];
2

2 Answers

2
votes

Use diff:

I = [0 0 1 0 1 1 0 0 0];
d = diff(I);
ind = [1 find(d~=0)+1]; %// starting index of each new value
rep = diff([ind numel(I)+1]); %// number of repetitions of each new value
J = [ I(ind).' rep.' ];
1
votes

Using strfind for a slightly bigger example -

I =[1 1 0 0 1 0 1 1 0 0 0 1 1 1 1 0 0]
zero_pos = ['0' num2str(bsxfun(@eq,I,0),'%1d') '0']
ind3 = [ strfind(zero_pos,'01') ; strfind(zero_pos,'10')]
counts = diff(ind3(:))

var = zeros(numel(counts),1);
var(2:2:end)=1;
J = [var counts];
if ind3(1,1)-1>0
    J = [1 ind3(1,1)-1;J];
end

Output

J =
     1     2
     0     2
     1     1
     0     1
     1     2
     0     3
     1     4
     0     2