MATLAB: How to find all possible combiantions of 3 numbers in a 6 number array using a for loop

homeworkMATLAB

I have a 6 number array, and I need to find all possible combinations of pulling 3 numbers out of it and seeing if they add up to 0 or not. I need to use a for loop, so I can't use things like nchoosek or randperm or numel. This is my code so far (with nchoosek as a substitue for where I'm going to put the for loop, just to make sure everything else works).
Matrix=[-4 2 1 -1 -1 0];
i=1;
Y=nchoosek(Matrix,3);
for i=1:20
if sum(Y(i,:))==0
disp(Y(i,:))
end
end
It prints out all the combinations just fine, but I have to use a for loop instead of a combination loop, and I have no clue how to.

Best Answer

There are probably more efficient ways of doing this, but here's one attempt:
Matrix=[-4 2 1 -1 -1 0];
n = numel(Matrix);
Y = zeros(0,3);
for first = 1:n
for second = first+1:n
for third = second+1:n
Y(end+1,:) = Matrix([first second third]);
end
end
end
Related Question