user3743235
user3743235

Reputation: 159

MATLAB Optimization - how to move on to next possible solution if a condition is not satisfied?

I am using the fmincon optimization to find parameters that fit constraints. It is currently set up like:

constraints = [1 2 3];    
interval = 100;

time_start = [2500];
time_boundary = [500 5000];
param2_start = [0.5];
param2_boundary = [0 1];

opts = optimset(optimset('fmincon'),'TolFun',1e-4,'TolX',1e-4,'display','iter');
[x,fval] = fmincon(@(X) func(X,constraints,interval),[time_start param2_start],[],[],[],[],[time_boundary(1) param2_boundary(1)],[time_boundary(2) param2_boundary(2)],[],opts)

where a simplified func is:

function out = func(X,constraints,interval)

  time = X(1);
  param2 = X(2);

  % Check inputs before calculations
  if (mod(time,interval) > 0)
      out = 999;
  else
      % Perform calculations based on parameters, constraints and interval.
      % Simplified to:
      out = time/interval;
  end

end

However, the function (func) can fail if time is not integer-divisible by interval.

Is there a way to catch this within the function so that fmincon moves onto another solution without failing?

Or, is there a better way to use fmincon (or another optimization tool) to avoid this issue?

Upvotes: 1

Views: 126

Answers (1)

houtanb
houtanb

Reputation: 4100

Yes, modify your function to something like (pseudo-code because you have not provided the contents of your function)

function(X, constraints, interval)
try
   <<code that can fail when function is being optimized>>
   <<time/interval when interval == 0 for example>>
catch
   return <<penalty value>>
end
end

Basically, the idea would be that when the function fails, you would return a penalty value so that the minimizer would move away from the values it passed to your function.


Edit: Based on your edit, the function would be:

function out = func(X, constraints, interval)
try
    out = X(1)/interval;
catch
    out = 1e10;
end
end

However, you will never end up in the catch portion of the block because the division will never cause an error, even if interval is NaN, Inf, or 0. I am only posting this because you asked me to. My understanding of a function "failing" is specifically that it throws an error. If it simply produces an incorrect result, then your function above is correct. I would just modify out in the failing case to be higher than any value you would obtain otherwise to train the minimizer to move away from this spot.

Upvotes: 2

Related Questions