2012-01-29 84 views
2

交替顺序我有一个像向量:发现在MATLAB

x = [0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 2 1 2 1 2 1 2 1 2 1 2 1 2 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1] 

我怎么能抢交替序列的开始和结束索引? (即1和2)

+0

你可以看看'ABS(DIFF( x))',并且对于长度至少为N的交替序列,这将是至少N个不等于0的相同数字的运行。 – 2012-01-29 01:02:19

+0

hmmm,报废 - 这将另外将1,3,5,7,...分类为交替序列。 – 2012-01-29 01:24:35

回答

1

我认为这是一个很酷的方法,但数值/数组方法会更快:P您可以使用正则表达式!

% convert into a space-separated string 
% (surely there's a better way than converting to cell array first?) 
str = strcat({num2str(x)}) 
% for some reason all elements are separated by more than one space, convert 
% so they're separated by a single space 
str = regexprep(str,' +',' ') 

% find start & end indices (into str) alternating sequences 
[s e]=regexp(str,'\<([^ ]+) ((?!\1)[^ ]+)(?: \1 \2)+(?: \1)?\>'),'start','end') 
% convert these indices into indices into `x` 
% (at the moment s & e include spaces) 
s = (cell2mat(s)+1)/2 
e = (cell2mat(e)+1)/2 

% run i is at x(s(i):e(i)) 
1

如果你知道你只有一个序列,它总是[1 2 ... 1 2],你可以简单地使用strfind

x = [0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 2 1 2 1 2 1 2 1 2 1 2 1 2 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1]; 

idx = strfind(x, [1 2]); 

start = idx(1); 
end = idx(end)+1; 

如果有可能多次出现,或者如果它并不总是1-2,或者如果序列是不完整的(例如,1 2 1,而不是1 2 1 2),你可以使用diff代替:

dx = diff(x); 
alt = dx(2:end)==-dx(1:end-1) & dx(1:end-1)~=0; 

starts = find(diff(alt)>0) + 1; 
ends = find(diff(alt)<0) + 2;