2012-02-08 14 views
2

私は、ベクトルを受け取る短いmatlab関数を書こうとしています。最長シーケンスの最初の要素のインデックスを返します(シーケンスは1と0で構成されていると見なすことができます)。例えば:解析シーケンスmatlab

IndexLargeSeq([110001111100000000001111111111110000000000000000000000000000000])

21を戻します - 1Sの最長シーケンスの第1の指標です。
はあなた
アリエルがあり

+1

興味深いですが質問はしませんでした。何を試しましたか? –

+1

密接に関連する/可能な重複:[順序でゼロの島を見つける](http://stackoverflow.com/q/3274043/52738) – gnovice

答えて

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) 

EDITx行または列ベクトルのいずれかとすることができる場合は、この場合の列ベクトルになり

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 

idxmaxSeqは1Sのこのsewuenceの長さです。 Aは行ベクトルでなければなりません。

データセットの蓄積方法(コマンドB = ...)を理解したい場合は、How to accumulate data-sets?をご覧ください。