MATLAB: How to generate N number of loops

for loop

Input: cell array of characters (e.g. 'IHQ')
Each individual character in the array is a variable in the code. For example,
I = {'AUU','AUC','AUA'}
H = {'CAU','CAC'}
Q = {'CAA','CAG'}
Output: all combinations of the elements of the arrays
For example:
B =
'AUUCAUCAA'
'AUUCAUCAG'
'AUUCACCAA'
'AUUCACCAG'
'AUCCAUCAA'
'AUCCAUCAG'
'AUCCACCAA'
'AUCCACCAG'
'AUACAUCAA'
'AUACAUCAG'
'AUACACCAA'
'AUACACCAG'
The way my code generates the combinations is in the following way:
k=1;
for i=1:length(I)
for j=1:length(H)
for m=1:length(Q)
B(k) = strcat(I(i), H(j), Q(m));
k=k+1;
end
end
end
This is, however, specific for the example input 'IHQ'. I want to code a more general way where the input can be of any length. Using this way, the number of for loops involved depends on the length of the input. I guess, is there any way I can make a for loop specifying the number of for loops. Or perhaps a different way to approach the output? Thanks!

Best Answer

I = {'AUU','AUC','AUA'};
H = {'CAU','CAC'};
Q = {'CAA','CAG'};
A = {I,H,Q};
A = A(:)';
n = cellfun('length',A);
nn = numel(n);
i0 = arrayfun(@(x)1:x,n,'un',0);
idx = cell(1,nn);
[idx{:}] = ndgrid(i0{end:-1:1});
i1 = fliplr(reshape(cat(nn,idx{:}),[],nn));
A1 = [A{:}];
ii = bsxfun(@plus,i1,[0,cumsum(n(1:end-1))]);
A2 = num2cell(A1(ii),1);
out = strcat(A2{:});
or
I = {'AUU','AUC','AUA'};
H = {'CAU','CAC'};
Q = {'CAA','CAG'};
A = {I,H,Q};
A = A(:)';
n = cellfun('length',A);
i0 = fullfact(n);
ii = bsxfun(@plus,i0,[0,cumsum(n(1:end-1))]);
A1 = [A{:}];
A2 = num2cell(A1(ii),1);
out = strcat(A2{:});