1
votes

I have an objective function that has 4 variables to solve for so that the output is minimal and I am having trouble understanding the syntax required to use the function "fminsearch" for solving for more than one variable. Here is my objective function:

function f4 = v4_objfunc(w_x,w_y,s_x,s_y)

f4 = 6*(w_x)^2 + 6*(w_y)^2 + 12*(s_x)^2 + 12*(s_y)^2 - 330*w_x - 228*w_y - 990*s_x -            
684*s_y - 6*w_x*s_x - 6*w_y*s_y + 86564;

end

That is the ".m" function file exactly as I have it saved. How do I use fminsearch to get the values of "w_x","w_y","s_x","s_y" that will result in the minimal outcome? If it helps any, the unknowns correspond to x-and-y values (for coordinates) and they only need to be checked between 0-100 (for all 4).

I have used the function page that Matlab offers, but have only understood how to use fminsearch for single-variable functions.

1

1 Answers

2
votes

Just use a vector to store your four scalars (I've also removed a bunch or extraneous parentheses):

function f4 = v4_objfunc(x)
w_x = x(1);
w_y = x(2);
s_x = x(3);
s_y = x(4);
f4 = 6*(w_x^2+w_y^2) + 12*(s_x^2+s_y^2) - 6*(w_x*s_x+w_y*s_y) ...
     - 330*w_x - 228*w_y - 990*s_x - 684*s_y + 86564;

Or directly with an anonymous function:

v4_objfunc = @(x)6*(x(1)^2+x(2)^2)+12*(x(3)^2+x(4)^2)-6*(x(1)*x(3)+x(2)*x(4)) ...
                 -330*x(1)-228*x(2)-990*x(3)-684*x(4)+86564;

x0 = ones(4,1);
[x,fval] = fminsearch(v4_objfunc,x0)
w_x = x(1);
w_y = x(2);
s_x = x(3);
s_y = x(4);