有一个长度序列的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
所以我在这里
由于非递减(或不增加)子序列的最大长度可以是15,所以我考虑通过向量x表示频率,对于不增加的子序列,用y表示频率:
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)将其扩展到长度L序列的一般情况,我想要遍历这个序列,并使用循环计算精确长度的子序列的频率。我该怎么做?我会创建长度为l的零向量,每当我遇到长度为l的子序列时,我会把1加到零矩阵的第1元素上。
因为我的序列长度是几千,所以我不会让Matlab来写它们,但是我会要求它写我特定的频率。
这样做好吗?在Matlab中是否有这样做的函数?
发布于 2015-04-06 17:43:35
那个可爱的单线解决方案怎么样?
%// 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)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 解释
%// 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);发布于 2015-04-06 17:43:22
对于非递减序列:
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));对于非递增序列,只需改变infs的不等式和符号:
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));https://stackoverflow.com/questions/29475674
复制相似问题