I must calculate an equation as follows:
where k1,k2
are given. I am using MATLAB to compute P
. I think I have a correct implementation fo
rahnema1's answer has a very good approach: create a table of values that you generate once and access later (as well as some other clever optimizations).
One thing I would change is the way the binomial coefficients are calculated. If you look at calculating the factorials for nchoosek(n, k)
and nchoosek(n, k+1)
, you're recalculating n!
both times, and for k+1
, you're recalculating k!
and multiplying it by k+1
. (Similarly for (n-k)!
.)
Rather than throw away the computations each time, we can iteratively compute nchoosek(n, k+1)
based on the value of nchoosek(n, k)
.
function L=combList(n, maxk)
% Create a vector of length maxk containing
% [nchoosek(n, 1), nchoosek(n, 2), ..., nchoosek(n, maxk)]
% Note: nchoosek(n, 0) == nchoosek(n, n) == 1
assert(maxk<=n, 'maxk must be less than or equal to n');
L = zeros(1,maxk);
L(1) = n; % nchoosek(n, 1) == n
for k = 2:maxk
L(k) = L(k-1)*(n-k+1)/k;
end
In your program, you would just create 3 lists for k1
, k2
, and k1+k2
with the appropriate limits, and then index into those lists to generate the sums.