- the complex approach is to write a recursive function,
- the simple approach is to use exactly one FOR-loop:
Create number of for loops depending on size of N
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi, i have a question regarding number of nested loops:
In this case N would be 4 and hence there are 4 for loops
But if N = 2 in need 2 for loops and the formula also changes to i_1+1_2/N where N=2
is it possible to create code that creates the correct amount of for loops (corresponding to the value of N)
and also changes the formula for i_value in a correct way.
i_Max = 8
i_value = [];
i_real = [];
i_first = [];
i_second = [];
i_third = [];
i_forth = [];
tol = 0.01;
i_good = false;
while i_good == false
% generate new ratio's
for i_1 = 1:0.1:i_Max
for i_2 = 1:0.1:i_Max
for i_3 = 1:0.1:i_Max
for i_4 = 1:0.1:i_Max
i_value(end+1) = (i_1+i_2+i_3+i_4)/N;
if (i_average-tol <i_value(end)) && (i_value(end)<i_average+tol)...
&& (i_1>i_2) && (i_2>i_3) && (i_3>i_4)
i_good =true;
i_real(end+1) = i_value(end);
i_first(end+1) = i_1;
i_second(end+1) = i_2;
i_third(end+1) = i_3;
i_forth(end+1) = i_4;
end
end
end
end
end
end
댓글 수: 4
채택된 답변
Image Analyst
2024년 5월 26일
OK, a not-clever but brainless and verbose approach is to just make a set of "if" blocks
if N == 2
% Code for N=2
elseif N == 3
% Code for N=3
elseif N == 4
% Code for N=4
end
Hopefully you have a small, known and limited number of possibilities for N, like 2, 3, or 4. If you have hundreds of possibilities then you should re-think your algorithm.
추가 답변 (1개)
Torsten
2024년 5월 26일
편집: Torsten
2024년 5월 26일
The N columns of the resulting C-matrix contain i_first, i_second,...
imax = 8;
N = 4;
i_average = (sum(0:N-1)/N+sum(imax:-1:imax-N+1)/N)/2;
tol = 0.5;
C = nchoosek(0:imax,N)
C = sort(C,2,'descend')
i_value = sum(C,2)/N
idx = abs(i_value-i_average)<tol
C = C(idx,:)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!