analyzing sequences matlab

2019-07-20 00:05发布

问题:

I am trying to write a short matlab function that will recieve a vector and will return me the index of the first element of the longest sequence of 1s (I can assume that the sequence consists of 1s and 0s). for example:

IndexLargeSeq([110001111100000000001111111111110000000000000000000000000000000])

will return 21 - which is the index of the first 1 of the longest sequence of 1s.
thank you
ariel

回答1:

Here is another option measuring distances between indices of 0s. The code takes into account situations if there are no 1s at all (returns empty vector), or if there are multiple sequences with the longest length. x is an input row vector.

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: If x can be either row or column vector, you can change the first line to

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

The output will be a column vector in this case.



回答2:

There you go:

% 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 than is the value (the index) you are looking for, maxSeq is the length of this sewuence of 1s. A has to be a row-vector.

If you want to understand how the datasets are accumulated (the command B = ...), look here: How to accumulate data-sets?.