Determine the number of "for" loops by the user

조회 수: 3 (최근 30일)
f4r3in
f4r3in 2021년 8월 27일
댓글: f4r3in 2021년 8월 30일
Hi everyone
I want to write a code that takes the number of uncertain parameters from the user and creates a "for" loop according to their number and performs the calculations.
for example:
The user enters the number 4 as the number of uncertainty parameters and the code puts 4 "for" loops in a row. This way :
for i=1:I
for j=1:J
for k=1:K
for r=1:R
"calculations"
end
end
end
end
Is this possible in MatLab?
  댓글 수: 4
f4r3in
f4r3in 2021년 8월 27일
Let me explain the problem further:
In the problem, the values I, J, K, R are known (for example all are equal to 7). And the calculation that is done in "for" loops is as follows: (A1 : A4 are also known)
"calculations"
Scen(:,l) = [A1(:,i);A2(:,j);A3(:,k);A4(:,r)];
l = l+1;
The only unknown issue is the number of "for" loops.
How can we implement this?
KSSV
KSSV 2021년 8월 27일
I think you can avoid using loops.....can you tell us what are those calculations?
I,J,K,R they will be always same?

댓글을 달려면 로그인하십시오.

채택된 답변

Chunru
Chunru 2021년 8월 27일
편집: Chunru 2021년 8월 27일
% The number of iterations
ni = [3 4 2 2]; % 4 iterations [I J K R]; i is innerest loop
idx = ones(size(ni)); % first index
k = cumprod(ni);
for i=1:prod(ni)
% calculate index (ignore this part if calculation independent of index)
ii = i;
for j=length(ni):-1:2
ir = rem(ii-1, k(j-1)) + 1;
idx(j) = (ii - ir) /k(j-1) + 1;
ii = ir;
end
idx(1) = ii;
disp(idx)
% do calculation depending on idx
end
1 1 1 1 2 1 1 1 3 1 1 1 1 2 1 1 2 2 1 1 3 2 1 1 1 3 1 1 2 3 1 1 3 3 1 1 1 4 1 1 2 4 1 1 3 4 1 1 1 1 2 1 2 1 2 1 3 1 2 1 1 2 2 1 2 2 2 1 3 2 2 1 1 3 2 1 2 3 2 1 3 3 2 1 1 4 2 1 2 4 2 1 3 4 2 1 1 1 1 2 2 1 1 2 3 1 1 2 1 2 1 2 2 2 1 2 3 2 1 2 1 3 1 2 2 3 1 2 3 3 1 2 1 4 1 2 2 4 1 2 3 4 1 2 1 1 2 2 2 1 2 2 3 1 2 2 1 2 2 2 2 2 2 2 3 2 2 2 1 3 2 2 2 3 2 2 3 3 2 2 1 4 2 2 2 4 2 2 3 4 2 2

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by