0

Iam a beginner in matlab. I have an array of numbers. Say 5 (4,2,1,4,3) Which means the variable 1 can take a value from 0 to 1, variable 2 can take a value 1,2 Variable 3 can take 0 and 1, Variable 4 can take from 0 to 4, Variable 5 can take from 0 t0 3.

I tried using "combntns" in matlab but it is a specific one and not like my case where each variable is having defined set of numbers. I need all combinations. I tried using for loop

for a=i1:-1:0
    for b=i2:-1:0
        for c =i3:-1:0
            for d=i4:-1:0
                for e = i5:-1:0
               com(j,1)=a;
                com(j,2)=b;
                com(j,3)=c;
                com(j,4)=d;
                com(j,5)=e;
                j=j+1;                    
            end
        end
    end
end

I dont want to use these many for loops. If my array size increases to 100 numbers, then it is a very big task to write 100 for loops. Can anyone suggest me with a code?

1 Answers1

0

I managed to solve your problem recursively in the following manner:

A = [ 0 1
      1 2
      0 1
      0 4
      0 3 ]; %// <= This is the example that you gave.

out = recursivePermutations(A,[]);

The function recursivePermutations is:

function out = recursivePermutations(boundsMat,previousCombos)

if size(boundsMat,1)==0
    out = previousCombos;
    return;
else
   lowBound = boundsMat(end,1);
   uppBound = boundsMat(end,2);
   tmp = (lowBound:uppBound)';

   if ~isempty(previousCombos)         
       tmp = [repmat(previousCombos,[length(tmp),1]),...
          reshape(repmat(tmp',[length(previousCombos),1]),...
          length(previousCombos)*length(tmp),1)];

   end   
   out = recursivePermutations(boundsMat(1:end-1,:),tmp);
end

The result is a vector of size 160*5. This corresponds to the number of possibilites you should get in this example (2*2*2*5*4).

Dev-iL
  • 23,742
  • 7
  • 57
  • 99