在数组中查找序列数 [英] Finding the # of sequences in an array
本文介绍了在数组中查找序列数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要报告数组中的序列数.例如:
I need to report the # of sequences in an array. For example:
A=[ 1 1 -1 -1 -1 -1 -1 0 1 -1 -1 -1 -1 1 1 -1 -1 1 0 1 1]
而且我必须报告一个数字连续出现的次数,例如
and I have to report the # of times a number comes consecutively, such as, one sequence of
5 -1s ([-1 -1 -1 -1 -1])
和一个序列
4 -1s ([-1 -1 -1 -1])
.
如何查找有多少个数字序列?
How can I find how many sequences of numbers there are?
推荐答案
您可以使用游程长度编码以执行此任务
You may use run-length encoding to perform this task
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
Applying run-length encoding to 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
的序列数感兴趣,那么您需要的是
So, if you are interested in the number of sequences of length > n
all you need is
>> nnz( rl > n )
这篇关于在数组中查找序列数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文