Matlab 中的双和

double sum in Matlab

我想写一个 Matlab 代码来计算以下内容:

\sum_{k=0}^{N-1} \frac{1}{k!} \sum_{i=0}^{k} {k \choose 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);