MATLAB: Substitute variable and find maximum of the function

optimization

Let's denote a function , where x and y belong to interval [1,5]. I would like to find maximum of this function, knowing that can have only two values : 0 or 1. So the code should check for what values of we can possibly get maximum and then calculate it within given intervat. At the end maximum should be printed.
My approach was to first substitute with permutations of 0 and 1, it's 4 combinations in total. Knowing we could find max within given intervals simply by creating a linspace
x = linspace(1,10);
for x and y, then meshgriding x and y, and in the end finding max using max(max(z)). The problem is, I don't know how to make a solution that will work fast enough to substitute 8 variables, for a more complicated function. I asked a similar question on this forum and this is the answer :
syms z(x,y) q1 q2
z(x,y)=(((sin(x).*(1+q1))./(3))+(1+q2))./(log10(y+1)-10);
A=perms([-1 1]);
c = linspace(1,5,100);
d=c;
[C,D] = meshgrid(c,d);
for i=1:size(A,1)
Z(x,y)=subs(z,{q1,q2},{A(i,1),A(i,2)})
Z_max(i) = max(max(double(vpa(Z(C,D),2))));
end
It works fine for , but it takes too much time to compute the result for 8 variables (,). The only thing that's needed is maximum.

Best Answer

The only function provided by Mathworks, of which I am aware, which can efficiently handle such mixed integer nonlinear programming problems is ga(): https://www.mathworks.com/help/gads/ga.html. However, you need to have global optimization toolbox to use this function
fun = @(x, q) (sin(x(1)).^2 + log(x(2)))./(x(1) + q(1) + q(2));
lb = [1;1;0;0]; % lower bounds
ub = [5;5;1;1]; % upper bounds
[sol, f] = ga(@(x) -fun(x(1:2), x(3:4)), 4, [], [], [], [], lb, ub, [], [3 4]);
Result:
>> sol
sol =
1.0000 5.0000 0 0
>> f
f =
-2.3175
Related Question