- 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
    6 views (last 30 days)
  
       Show older comments
    
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 Comments
Accepted Answer
  Image Analyst
      
      
 on 26 May 2024
        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.
More Answers (1)
  Torsten
      
      
 on 26 May 2024
        
      Edited: Torsten
      
      
 on 26 May 2024
  
      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 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!


