具有一系列长度为L
的数字,我需要计算有多少非精确长度的非递减和非递增子序列。例如,如果我有一个长度为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 的子序列时,我会在零矩阵的 l -th元素中加1。< / p>
由于我的序列长度只有几千,我不会要求Matlab写这些,但我会要求它给我写特定的频率。
这是一个好方法吗? Matlab中是否有一些功能正在执行此操作?
答案 0 :(得分:2)
那个可爱的单线解决方案怎么样?
%// 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);
答案 1 :(得分:1)
对于非递减序列:
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));
对于非增加序列,只需改变inf
s的不等式和符号:
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));