How to generate N number of loops
이전 댓글 표시
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!
채택된 답변
추가 답변 (1개)
Azzi Abdelmalek
2013년 8월 19일
편집: Azzi Abdelmalek
2013년 8월 19일
%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'
카테고리
도움말 센터 및 File Exchange에서 Specialized Power Systems에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!