1

I have n vectors with some numbers (n is a random number) How I can determine all combinations of all numbers I have? ex:

    a=0;
    for i=1:length(vector1)
      for j=1:length(vector2)
        for k=1:length(vector3)
          ... (n times)
          a=a+1;
          M{a}=[i,j,k,...];
        end
      end
    end
Cecilia
  • 4,512
  • 3
  • 32
  • 75
mona
  • 101
  • 6
  • may be try http://www.mathworks.com/help/map/ref/combntns.html – Nasser Mar 16 '15 at 12:28
  • I've interpreted your question to be about how best to get all combinations rather than how to execute a random number of for-loops. If this isn't what you need, please let me know. – Cecilia Mar 16 '15 at 16:30

1 Answers1

2

One possiblity combvec. This function gives you all combinations of the column vectors of the input matrices. You can do the following to get the combinations of elements in your random vectors.

vector1 = random('Normal', 0, 1, 1, 5);
vector2 = random('Normal', 0, 1, 1, 5);
vector3 = random('Normal', 0, 1, 1, 5);
M = combvec(vector1, vector2, vector3);

M will be a 3x125 matrix where each column is one element from vector1, one element from vector2, and one element from vector3

If you want n vectors, where n is a random number, an alternative approach is using cartesian product to index into the vectors.

n = randi(5);
all_vectors = random('Normal', 0, 1, n, 5);
indices = mat2cell(repmat([1:5], n, 1), ones(n ,1))';
[x y z] = ndgrid(indices{:});
cartProd = [x(:), y(:), z(:)];
M = all_vectors(cartProd);
Community
  • 1
  • 1
Cecilia
  • 4,512
  • 3
  • 32
  • 75