Arrays 非递增和非递减子序列的频率
有一个长度为Arrays 非递增和非递减子序列的频率,arrays,algorithm,matlab,sequences,Arrays,Algorithm,Matlab,Sequences,有一个长度为L的数字序列,我需要计算有多少个精确长度的非递减和非递增子序列。例如,如果我有一个长度为15的序列 2, 4, 11, 13, 3, 5, 5, 6, 3, 3, 2, 4, 2, 14, 15 我看到非递增子序列是 13, 3 6, 3, 3 , 2 4, 2 非递减子序列是 2, 4, 11, 13 3, 5, 5, 6 2, 4 2, 14, 15 所以我有 2长度为2的非递增子序列 1长度为4的非递增子序列 2长度为2的非递减子序列 1长度为3的非递减子序列 2长度为4的非
L
的数字序列,我需要计算有多少个精确长度的非递减和非递增子序列。例如,如果我有一个长度为15的序列
2, 4, 11, 13, 3, 5, 5, 6, 3, 3, 2, 4, 2, 14, 15
我看到非递增子序列是
13, 3
6, 3, 3 , 2
4, 2
非递减子序列是
2, 4, 11, 13
3, 5, 5, 6
2, 4
2, 14, 15
所以我有
- 2长度为2的非递增子序列
- 1长度为4的非递增子序列
- 2长度为2的非递减子序列
- 1长度为3的非递减子序列
- 2长度为4的非递减子序列
x = (0,2,0,1,0,0,0,0,0,0,0,0,0,0,0)
y = (0,1,1,2,0,0,0,0,0,0,0,0,0,0,0)
x = [2, 4, 11,13,3,5,5,6,3,3,2,4,2,14,15]; %// data
y = [inf x -inf]; %// terminate data properly
starts = find(diff(y(1:end-1))<0 & diff(y(2:end))>=0);
ends = find(diff(y(1:end-1))>=0 & diff(y(2:end))<0);
result = histc(ends-starts+1, 1:numel(x));
将其扩展到长度为L的序列的一般情况,我想遍历该序列,并使用循环来计算精确长度的子序列的频率。我该怎么做?我将创建长度为L的零向量,每次我遇到长度为L的子序列时,我将向零矩阵的第L个元素添加1
由于我的序列长度为几千,我不会要求Matlab编写它们,但我会要求它编写特定的频率
这是一个好方法吗?
Matlab中是否有一些函数可以执行此操作?对于非递减序列:
x = (0,2,0,1,0,0,0,0,0,0,0,0,0,0,0)
y = (0,1,1,2,0,0,0,0,0,0,0,0,0,0,0)
x = [2, 4, 11,13,3,5,5,6,3,3,2,4,2,14,15]; %// data
y = [inf x -inf]; %// terminate data properly
starts = find(diff(y(1:end-1))<0 & diff(y(2:end))>=0);
ends = find(diff(y(1:end-1))>=0 & diff(y(2:end))<0);
result = histc(ends-starts+1, 1:numel(x));
那个可爱的单线解决方案怎么样
%// vector
A = [2, 4, 11, 13, 3, 5, 5, 6, 3, 3, 2, 4, 2, 14, 15]
%// number of digits in output
nout = 15;
seqFreq = @(vec,x) histc(accumarray(cumsum(~(-x*sign([x*1; diff(vec(:))]) + 1 )), ...
vec(:),[],@(x) numel(x)*~all(x == x(1)) ),1:nout).' %'
%// non-increasing sequences -> input +1
x = seqFreq(A,+1)
%// non-decreasing sequences -> input -1
y = seqFreq(A,-1)
解释
当你认为[ 3 3 ]为非递减时,你也应该考虑[ 5,5 ]为非递增。否则就很难了
x
将是x=(0,3,0,1,0,0,0,0,0,0,0,0,0,0)
然后,就像在两个答案中一样。我犯了一个错误。谢谢你指出这一点。3,3与6,3,3,2搭配,5,5与3,5,5,6搭配。事实上,我不能将3,3或5,5归类为非递减或非递增序列,因为它们是常数。我要把这个问题更正一下。我会尝试这个代码,我会告诉你它是否有效。非常感谢。嗯,你应该称之为“增加”和“减少”,而不是“非减少”和“非增加”,实际上不。非减少意味着它在增加,但可以包括恒定的子序列。你似乎不知道你想要什么
%// example for non-increasing
q = +1;
%// detect sequences: value = -1
seq = sign([q*1; diff(A(:))]);
%// find subs for accumarray
subs = cumsum(~(-q*seq + 1));
%// count number of elements and check if elements are equal, if not, set count to zero
counts = accumarray(subs,A(:),[],@(p) numel(p)*~all(p == p(1)) );
%// count number of sequences
x = histc(counts,1:nout);