% Much more efficient MxN: % Note, we rotate the matrix here so rows and columns are also swapped, % this is because the reshape function reads column-wise. % Uses combn function: % http://www.mathworks.com.au/matlabcentral/fileexchange/7147-combn-4-3 n = 2; % number of rows m = 3; % number of columns num_list = [0 1 2]; % List of numbers to choose from. num_com = size(num_list,2) .^ (m*n); %Total number of combinations output = mat2cell(reshape(combn(num_list, m*n)', n, m*num_com), n, repmat(m,1,num_com));