how to count the number of function calls without modifying it by inserting a counter ?
    8 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    genevois pierre
 el 10 de Oct. de 2018
  
Hi, for example in ga(...), the count of objective function calls is provided, but not that of the constraint function. My unsatisfactory solution is, in the main program, to insert a global variable to count and another to reset the counter :
      global constr_count 
      global reset_constr_count    % = 1 to reset
      ...
      reset_constr_count = 1;
      [x, fval, exitflag, output] = ga(handle_obj, I, ...
          [], [], [], [], lx, ux, @my_constraint_function, options_ga);
and to insert those lines in the constraint function :
      function [g, h] = my_constraint_function(x)
      ...
      % counter constr_count of calls to this function :
      global constr_count reset_constr_count;
      persistent count;
      if isempty(count) || reset_constr_count == 1
          count = 1;
          reset_constr_count = 0;
      else
          count = count + 1;
      end
      constr_count = count;
With this solution, I have to modify all my pre existing constraint functions, which is a hard task. Is there an easier way to count (not only in that ga example) ? Thank you !
0 comentarios
Respuesta aceptada
  Matt J
      
      
 el 10 de Oct. de 2018
        
      Editada: Matt J
      
      
 el 10 de Oct. de 2018
  
      If you just provide a wrapper for your constraint function to ga(), then you can handle the counter there instead of changing your legacy constraint code. Also, if you make the wrapper a Nested Function like below, then there will be no need for global, persistent, or reset variables, and the control logic simplifies to one line:
 function do_Optimization
   constr_count=0; %externally scoped variable
   x=ga(@fitnessfun,nVars,...,@my_constraint_wrapper);
        function [g, h] = my_constraint_wrapper(x)  %NESTED
           constr_count = constr_count +1 ;
            [g,h]= my_constraint_function(x);
        end
 end
0 comentarios
Más respuestas (1)
Ver también
Categorías
				Más información sobre Entering Commands en Help Center y File Exchange.
			
	Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

