How to generate N number of loops
2 views (last 30 days)
Show older comments
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!
0 Comments
Accepted Answer
Andrei Bobrov
on 19 Aug 2013
Edited: Andrei Bobrov
on 20 Aug 2013
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{:});
0 Comments
More Answers (1)
Azzi Abdelmalek
on 19 Aug 2013
Edited: Azzi Abdelmalek
on 19 Aug 2013
%or more general
I = {'AUU','AUC','AUA'};
H = {'CAU','CAC'};
Q = {'CAA','CAG'};
L={'s1','s2','s3'};
v={I,H,Q,L}
v0=v{1};
for k=1:numel(v)-1
v1=v{k+1};
[ii1,ii2]=ndgrid(1:numel(v0),1:numel(v1));
v0= strcat(v0(ii1(:)),v1(ii2(:)));
end
out=v0'
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!