MATLAB: Creating a Variable Number of Nested ‘for’ Loops

for loopMATLAB

Hi all,
I am trying to iterate down every column of array x, and extract all combinations when the sum of these elements is equal to one.
At the moment this is being made possible by having a for loop iterate down each individual column, and then using an if statement to pause the loop and store these combinations in the array 'Combinations'.
N = 3;
x = zeros(6, N);
x(1, :) = 0;
x(2, :) = 0.2;
x(3, :) = 0.4;
x(4, :) = 0.6;
x(5, :) = 0.8;
x(6, :) = 1;
a = 0;
A = 1;
for i = 1:size(x, 1)
for j = 1:size(x, 1)
for k = 1:size(x, 1)
X = x(i, 1) + x(j, 1) + x(k, 1);
if X == 1
Combinations(A, 1) = x(i, 1);
Combinations(A, 2) = x(j, 2);
Combinations(A, 3) = x(k, 3);
a = a + 1;
A = A + 1;
continue
end
end
end
end
However, if the number of columns in x were to change, I would need to be able to vary the number of for loops depending on the value of N. Is this possible/is there an alternative method of achieving a similar result?
Any help would be appreciated. Thanks!

Best Answer

Use https://www.mathworks.com/matlabcentral/fileexchange/10064-allcomb-varargin- allcomb() from the File Exchange, and then throw away the entries that do not match your constraint.