How to generate N number of loops
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!
Accepted Answer
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'
Categories
Find more on Specialized Power Systems 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!