matlabsumbinomial-coefficients

double sum in Matlab


I would like to write a Matlab code to calculate the following:

\sum_{k=0}^{N-1} \frac{1}{k!} \sum_{i=0}^{k} {k \choose i}(a-1)^{k-i} a^k

and my code is:

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' variable gives different value when it is inside the for loop rather than outside. But I want it to calculate when k = 0:N-1. What am I doing wrong?

Thank you.


Solution

  • The issue is your current code overwrites all on every iteration. Moving it outside the loop also doesn't work because you'll only save the result of the last iteration.

    To save the all of every iteration, define all as a vector and then assign each intermediate result into that vector:

    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);