Search code examples
matlabfor-loopvectorization

Automatic way to code several for loops in MATLAB


I have the following sum :

Click here to see the sum!

I am computing this sum in MATLAB as follows:

k = 100;
count = 1;
for i1 = 0 : k
    for i2 = 0 : k - i1
        for i3 = 0 : k - i1 - i2
            for i4 = 0 : k - i1 - i2 - i3
                count = count + 1;
            end
        end
    end
end

My question is how can I do this in a more automatic way without manually adding a for loop each time with the indices? For example, is there a way to vectorize this problem?

I want to apply the same concept but until i100, of course I am not going to manually add 100 for loops! So how can I write another version of this MATLAB code that helps me vectorize the above code?

Thank you in advance!


Solution

  • I think you can already know the answer from the comment that I posted. But here's the elaboration and the code.

    To start, let's look at the problem from the smallest loop k-n to the biggest loop k:

    • The smallest loop sums up the count to k-n, let's call that value Xn for convinience. Remember that Xn = k-(n).
    • The second smallest loop sums the value gotten by the smallest loop k-(n-1) times. Now the sum is up to [k-(n-1)]*Xn.
    • We keep going until the biggest loop, where the total sum that was achieved so far is repeated k-0 times.

    Reminds you of something? Looks a lot like a factorial, but also not really since it stops eventually and doesn't go all the way down to 1, though it can if you set the right values.

    The sum that you are trying achieve is basically the binomial theorem and you can achieve it with the nchoosek MATLAB function. This would give you the desired results:

    nchoosek(n + k, k)

    For n = 4 and k=100 you will get 4598126. From your code you get the same value with one added since your count starts at 1 and not at 0, is this a joke related to MATLAB indexing?! JK, we have fun here..