我想写一个Matlab代码来计算以下内容:
\sum_{k=0}^{N-1}\frac{1}{k!}\sum_{i=0}^{k}{k\选择i}(a-1(^{k-i}a ^k
我的代码是:
N = 3;
a = [3 4];
for k = 0:N-1
f = 0;
for i = 0:k
f = f + nchoosek(k,i).* a.^k .* (a-1).^(k-i);
end
sumoff = sum(f);
all = (( 1./ (factorial(k))).*sumoff);
end
overall= sum(all);
当"all"变量在for循环内部而不是外部时,它会给出不同的值。但我想让它在k=0:N-1时进行计算。我做错了什么?
谢谢。
问题是当前代码在每次迭代中都会覆盖all
。将它移到循环之外也不起作用,因为您只会保存上一次迭代的结果。
要保存每次迭代的all
,请将all
定义为一个向量,然后将每个中间结果分配到该向量中:
N = 3;
a = [3 4];
% preallocate a vector for `all`
all = nan(N-1, 1);
for k = 0:N-1
f = 0;
for i = 0:k
f = f + nchoosek(k,i) .* a.^k .* (a-1).^(k-i);
end
sumoff = sum(f);
% assign your intermediate result into the `all` vector
all(k+1) = ((1./(factorial(k))) .* sumoff);
end
overall = sum(all);