MATLAB: Help with Grid Search optimization method.

optimization grid search

Hey, i want to make an optimization script using the grid search method, this is what i have so far:
syms x
syms y
f=input('Write the function in terms of X y Y: ')
x1=input ('Write the lower x limit: ' )
y1=input ('Write the lower y limit: ')
x2=input ('Write the upper x limit: ')
y2=input ('Write the upper y limit: ')
dx=1000;
dy=1000;
xi=(x2-x1)/dx;
yi=(y2-y1)/dy;
max=-10000000;
x=x1;
for i=0:dx;
y=y1;
for j=0:dy;
f=subs(f,[x,y],[xi,yi]);
if f>max
max=f;
xmax=x;
ymax=y;
end
y=y+yi;
end
x=x+xi;
end
disp('The max value of the function is : ', num2str(max));
But i get the following error:
Conversion to logical from sym is not possible.
Error in gsopt (line 18)
if f>max
What is wrong with my algorithm? Can you help me?
Thanks in advance.

Best Answer

You have
syms x
syms y
so at this point x and y and symbolic
x1=input ('Write the lower x limit: ' )
y1=input ('Write the lower y limit: ')
so x1 and y1 are numeric
x=x1;
and that overwrites the symbolic x with a numeric value so x is no longer symbolic for any new references to x
for i=0:dx;
y=y1;
and that overwrites the symbolic y with a numeric value so y is no longer symbolic for any new references to y
for j=0:dy;
f=subs(f,[x,y],[xi,yi]);
those are new references to x and y, so the numeric values are substituted . The first time through, the command is effectively
f = subs(f, [x1, y1], [xi, yi])
which, if it has any effect at all, would be to change one numeric value in f to a different numeric value, leaving the symbols x and y in the function alone. The symbols x and y in the function are existing references to x and y, not new references to x and y, so they retained their symbolic identity within the function.
The moral of the story: avoid assigning a numeric value to a symbolic variable, because it just gets too confusing about whether the variable name refers to a symbolic value or the numeric value.
Note too that if the subs() worked, you would be overwriting your f with the substituted f, and leaving no variables to be substituted in your next iteration.
Do you really want to substitute the increments xi and yi ?? What for?
Hint: look at matlabFunction()
Related Question