我有一个矢量,比如Y2。我想找到一些订单的产品总和,比如说10。一种天真的方式如下。在matlab中有一个很好的方法吗?
for tt=1:length(Y2)-10
LHS(tt) = Y2(tt) + Y2(tt)*Y2(tt+1) + Y2(tt)*Y2(tt+1)*Y2(tt+2) + Y2(tt)*Y2(tt+1)*Y2(tt+2)*Y2(tt+3) ...
+ Y2(tt)*Y2(tt+1)*Y2(tt+2)*Y2(tt+3)*Y2(tt+4) + Y2(tt)*Y2(tt+1)*Y2(tt+2)*Y2(tt+3)*Y2(tt+4)*Y2(tt+5) ...
+ Y2(tt)*Y2(tt+1)*Y2(tt+2)*Y2(tt+3)*Y2(tt+4)*Y2(tt+5)*Y2(tt+6) ...
+ Y2(tt)*Y2(tt+1)*Y2(tt+2)*Y2(tt+3)*Y2(tt+4)*Y2(tt+5)*Y2(tt+6)*Y2(tt+7) ...
+ Y2(tt)*Y2(tt+1)*Y2(tt+2)*Y2(tt+3)*Y2(tt+4)*Y2(tt+5)*Y2(tt+6)*Y2(tt+7)*Y2(tt+8) ...
+ Y2(tt)*Y2(tt+1)*Y2(tt+2)*Y2(tt+3)*Y2(tt+4)*Y2(tt+5)*Y2(tt+6)*Y2(tt+7)*Y2(tt+8)*Y2(tt+9);
end
答案 0 :(得分:1)
这是一个O(n)
的解决方案:
<强> order_prod_sum.m 强>
function [ result ] = order_prod_sum( v, k )
result = zeros(length(v)-k,1);
last = 1;
for i = 1:k
last = last * v(i);
result = result + last;
end
n = length(v) - k;
for i = 2:n
cur_sum = result(i-1)/v(i-1) -1;
last = v(i+k-1) * last / v(i-1);
result(i) = last + cur_sum;
end
end
<强>比较强>
three_loops.m (您的解决方案)
function [ result ] = three_loops(v, k)
result = zeros(length(v)-k,1);
for tt=1:length(v)-k
for j=0:k-1
for i=0:j
YY = prod(v(tt:tt+i));
end
result(tt) = result(tt)+ YY;
end
end
end
k=10;
Num = 100000;
v = randi(10,1,Num);
tic;
result1 = three_loops(v, k);
toc;
tic
result2 = order_prod_sum(v, k);
toc;
assert(sum(result1-result2) == 0)
<强>输出强>
Elapsed time is 4.739388 seconds.
Elapsed time is 0.005321 seconds.
答案 1 :(得分:0)
这将完成这项工作:
k=10;
LHS = zeros(T-k-1,1);
for tt=1:length(Y2)-k
for j=0:k-1
for i=0:j
YY = prod(Y2(tt:tt+i));
end
LHS(tt) = LHS(tt)+ YY;
end
end