1

我需要报告数组中的序列数。例如:

A=[ 1 1 -1 -1 -1 -1 -1 0 1 -1 -1 -1 -1 1 1 -1 -1 1 0 1 1]

我必须报告一个数字连续出现的次数,例如,一个序列

5 -1s ([-1 -1 -1 -1 -1])和一个序列

4 -1s ([-1 -1 -1 -1]).

我怎样才能找到有多少个数字序列?

4

2 回答 2

1

您可以使用游程编码来执行此任务

function [rl data] = runLength( vec )
% run length encoding for vector vec
rl = ( find( vec ~= [vec(2:end), vec(end)+1] ) );
data = vec( rl );
rl(2:end) = rl(2:end) - rl(1:end-1);

将游程编码应用于A

>> [rl data] = runLength( A )
rl =
   [ 2 5 1 1 4 2 2 1 1 2 ]
data =
   [ 1 -1 0 1 -1 1 -1 1 0 1 ]

因此,如果您对长度的序列数感兴趣 >n您只需要

>> nnz( rl > n )
于 2013-02-12T12:41:41.473 回答
0

If you only have a few number of possible element values in A (as in the example in the question where there only are three values, -1, 0 and 1) you could loop through these and use the following few steps to get the lengths of the different sequences.

Here is an example checking A == -1:

A = [1 1 -1 -1 -1 -1 -1 0 1 -1 -1 -1 -1 1 1 -1 -1 1 0 1 1];
B = [0, A==-1, 0];

Use the diff() function to find the beginning and end of each sequence and subtract the two vector to get the sequence lengths.

>> C = find(diff(B)==-1)-find(diff(B)==1)

C =

     5     4     2

Here we can see that there is one sequence of length five, followed by one of length four and one of lenth two. We could also use histc() to get the frequency of these lengths in a vector.

>> D = histc(C,1:max(C))

D =

     0     1     0     1     1

Repeating the procedure with another value, for example checking B = [0, A==1, 0]; gives us:

C =

     2     1     2     1     2

D =

     2     3
于 2013-02-12T12:26:47.010 回答