我有一个像:
这样的矢量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 :(得分: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)
如果你知道你只有一个序列,并且它总是[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;