2012-02-08 32 views
2

我想寫一個簡短的matlab函數,它將接收一個向量,並且會返回1s中最長序列(我可以假設該序列由1和0組成)的第一個元素的索引。例如:分析序列matlab

IndexLargeSeq([110001111100000000001111111111110000000000000000000000000000000])

將返回21 - 這是1秒的最長序列的第一1的索引。
謝謝
林依晨

+1

有趣,但你沒有問一個問題。你嘗試了什麼? – 2012-02-08 11:45:38

+1

密切相關/可能重複:[查找序列中零的島嶼](http://stackoverflow.com/q/3274043/52738) – gnovice 2012-02-08 16:09:12

回答

0

這是測量0之間的距離之間的距離的另一種選擇。如果根本沒有1(返回空向量),或者如果有多個長度最長的序列,代碼將考慮情況。 x是輸入行向量。

idx = find([1 ~x 1]); %# indices of 0s +1 
idxdiff = diff(idx); %# lengths of sequences (+1) 
maxdiff = max(idxdiff); 
if maxdiff == 1 
    maxseqidx = []; %# no 1s at all 
else 
    %# find all longest sequences, may be more then one 
    maxidx = find(idxdiff == maxdiff); 
    maxseqidx = idx(maxidx); 
end 
disp(maxseqidx) 

EDIT:如果x可以是行或列向量,可以將第一線改變爲

idx = find([1; ~x(:); 1]); 

的輸出將是在這種情況下的列向量。

1

你去那裏:

% input: 
A = [0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1]'; 

% replace 0 with 2 because the next command doesn't work with '0' as values 
A(A == 0) = 2; 

% accumulate data sets 
B = [A(diff([A; 0]) ~= 0), diff(find(diff([0; A; 0])))]; 

% maximize second column where first column == 1 
maxSeq = max(B(B(:, 1) == 1, 2)); 

% get row of B where first column == 1 && second column == maxSeq 
row = find(B(:,1) == 1 & B(:,2) == maxSeq, 1); 

% calculate the index of the first 1s of this longest sequence: 
idx = sum(B(1:(row-1),2)) + 1 

idx比是你正在尋找的值(指數),maxSeq是這個sewuence 1秒的長度。 A必須是行向量。

如果您想了解數據集的累積方式(命令B = ...),請看這裏:How to accumulate data-sets?