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)
交替順序我有一個像向量:發現在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)
我認爲這是一個很酷的方法,但數值/數組方法會更快: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 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;
你可以看看'ABS(DIFF( x))',並且對於長度至少爲N的交替序列,這將是至少N個不等於0的相同數字的運行。 – 2012-01-29 01:02:19
hmmm,報廢 - 這將另外將1,3,5,7,...分類爲交替序列。 – 2012-01-29 01:24:35