题目:
来源于Mathwork上的Cody,Problem 55 - Counting Sequence,
代码实现,
function y = CountSeq(x)
if length(x)==1
y=[1,x];
else
a=1;b=x(1);y=[];
for i=2:length(x)
if x(i)==x(i-1)
a=a+1;
else
y=[y,[a,b]];
a=1;
b=x(i);
end
end
if x(end)==x(end-1)
y=[y,[a,b]];
else
y=[y,[1,x(end)]];
end
end
end
需要注意的是开头y的初始化,以及对x(end)的处理。
以下是测试结果,
>> clear;x = [5 5 2 1 1 1 1 3];CountSeq(x)
ans =
2 5 1 2 4 1 1 3
>> clear;x = [9];CountSeq(x)
ans =
1 9