Algorithm for finding all nonnegative integer solutions of $x_1 + x_2 + x_3 = 4$ I need an algorithm to show all the solutions of $x_1+x_2+x_3=4$ to write a MATLAB program. I don't want to use random function. (I wrote a program with random function, but is very slow)
please help me.
I need to show something like this(this is the result with random function)
 1     3     0
 3     0     1
 0     0     4
 1     2     1
 2     2     0
 1     0     3
 0     4     0
 0     3     1
 1     1     2
 4     0     0
 0     2     2
 0     1     3
 3     1     0
 2     0     2
 2     1     1

 A: Here is a solution in Python where you can set $N$ and $S$ as you want :
N = 3 # Number of variables
S = 4 # Sum of variables


def f(array,n):
    s = sum(array)
    if n == 1:
        print array + [S-s]
    else:
        for i in xrange(0,S+1-s):
            f(array + [i],n-1)

f([],N)

This should in theory be optimal since there are no if-statements that could discard any computation.
A: Use recursion on the number of terms. The first term $x_1$ can be $0$, $1$, $2$, $3,$ or $4$, and for a given choice of$~x_1$, the remaining terms run though all solutions of $x_2+x_3=4-x_1$.
The function does not have to be recursive if the depth is fixed, as in your example. Simply
for i from 0 to 4
  for j from 0 to 4-j
    print (i, j, 4-i-j)

will do (sorry I don't speak MATLAB, but I hope you get the idea). If you want the number of terms to be given in a variable, the depth is not fixed and you need recursion (with a recursive call inside a loop) to obtain the effect of an unknown number of nested loops.
