Is there a command or one-line strategy in MATLAB that will return all the combinations of the components of n
cell arrays, taken n
at a time?
Although I address this in my answer to a related/near duplicate question, I'm posting a different version of my solution here since it appears you want a generalized solution, and my other answer is specific for the case of three input sets. Here's a function that should do what you want for any number of cell array inputs:
function combMat = allcombs(varargin)
sizeVec = cellfun('prodofsize', varargin);
indices = fliplr(arrayfun(@(n) {1:n}, sizeVec));
[indices{:}] = ndgrid(indices{:});
combMat = cellfun(@(c,i) {reshape(c(i(:)), [], 1)}, ...
varargin, fliplr(indices));
combMat = [combMat{:}];
end
And here's how you would call it:
>> combMat = allcombs(A, B)
combMat =
'a1' 'b1'
'a1' 'b2'
'a1' 'b3'
'a2' 'b1'
'a2' 'b2'
'a2' 'b3'
A 2-line strategy:
A = {'a1','a2'};
B = {'b1','b2','b3'};
[a b]=ndgrid(1:numel(A),1:numel(B));
C= [A(a(:))' B(b(:))']
C =
'a1' 'b1'
'a2' 'b1'
'a1' 'b2'
'a2' 'b2'
'a1' 'b3'
'a2' 'b3'