MATLAB: How to obtain all possible combinations of given values in vector

combinationsMATLAB

I want to obtain all possible combinations of valies of given vector . If V=[v1 v2 … vr] where r= length(V) then
Allcom=[0 0 0 0 ]
0 0 0 .. 1 ;
………… ;
0 0 vr ;
… ……… ;
v1 v2 … vr]
For example, to generate the following vector V=[1 2] and r=2.
Allcom=[0 0 ;
0 1 ;
0 2 ;
1 0 ;
1 1 ;
1 2]

Best Answer

v =[2 4 8 3]; %for example
c = arrayfun(@(x) 0:x, v, 'UniformOutput', false);
[c{:}] = ndgrid(c{:});
allcombs = cell2mat(cellfun(@(x) x(:), c, 'UniformOutput', false)) %optionally wrapped in sortrows