考虑由1和0组成的索引向量:
I=[0 0 1 0 1 1 0 0 0];
如何在matlab中轻松生成以下矩阵:
J=[0 2;
1 1;
0 1;
1 2;
0 3];
答案 0 :(得分:2)
使用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 :(得分:1)
使用strfind
作为更大的示例 -
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
<强>输出强>
J =
1 2
0 2
1 1
0 1
1 2
0 3
1 4
0 2