MATLAB: How generate combination list of 4 independent vectors

combinationlist

Hello,
I have a question. I am trying to generate list of 4 vectors. For example v1=[ 1; 2; 3, 4]; v2=[ 5; 6; 7]; v3=[ 8; 9]; v4=[ 10] will generate matrix with 24 rows (number of possible combinations) and with 4 columns.
I tried to use 4 for-loops, but when input vectors have more elements (200 elements for each vector), the algorithm is starting to be slow. I would like to ask you for a help. Is there any other possible way or a matlab function to create this thing?
Thank You, Dominik.
M1_idx=[1; 2; 3; 4]; M2_idx=[5; 6; 7]; M3_idx=[8; 9]; M4_idx=[10];
[r1,c1] = size(M1_idx);
[r2,c2] = size(M2_idx);
[r3,c3] = size(M3_idx);
[r4,c4] = size(M4_idx);
K_mat = zeros(r1*r2*r3*r4,c1+c2+c3+c4);
for i=1:r1
for j=1:r2
for k=1:r3
for l=1:r4
K_mat((i-1)*r2*r3*r4 + (j-1)*r3*r4 + (k-1)*r4 + l,:) = [M1_idx(i) M2_idx(j) M3_idx(k) M4_idx(l)];
end
end
end
end

Best Answer

A simple solution for a fixed number of vectors:
>> [x1,x2,x3,x4] = ndgrid(v1,v2,v3,v4);
>> M = [x1(:),x2(:),x3(:),x4(:)]
M =
1 5 8 10
2 5 8 10
3 5 8 10
4 5 8 10
1 6 8 10
2 6 8 10
3 6 8 10
4 6 8 10
1 7 8 10
2 7 8 10
3 7 8 10
4 7 8 10
1 5 9 10
2 5 9 10
3 5 9 10
4 5 9 10
1 6 9 10
2 6 9 10
3 6 9 10
4 6 9 10
1 7 9 10
2 7 9 10
3 7 9 10
4 7 9 10
A general solution which expands to any number of vectors (which should be stored in one cell array, as using numbered variables invariably leads to inefficient code):
>> C = {v1,v2,v3,v4}; % vectors should be stored in one cell array.
>> [C{:}] = ndgrid(C{:});
>> M = cell2mat(cellfun(@(m)m(:),C,'uni',0))
M =
1 5 8 10
2 5 8 10
3 5 8 10
4 5 8 10
1 6 8 10
2 6 8 10
3 6 8 10
4 6 8 10
1 7 8 10
2 7 8 10
3 7 8 10
4 7 8 10
1 5 9 10
2 5 9 10
3 5 9 10
4 5 9 10
1 6 9 10
2 6 9 10
3 6 9 10
4 6 9 10
1 7 9 10
2 7 9 10
3 7 9 10
4 7 9 10