neoborg
neoborg

Reputation: 11

why do i get fminsearch undefined function error

I'm trying to optimize a function with 2 inputs. Trying to use fminsearch but it keeps saying undefined function or variable although it is already defined.

I have already defined the function in a separate script that is in the same directory with my main script. I have a classroom license which includes optimization toolbox and there is no spelling mistake while calling the function.

function o=u(x,y)  
%some code here
end

%in a second script

init=[0.1,0.1];

b=fminsearch(o,init);

The error is:

Undefined function or variable 'o'.

Upvotes: 1

Views: 567

Answers (1)

SecretAgentMan
SecretAgentMan

Reputation: 2854

From the documentation on fminsearch, the function being minimized must have a single argument and accessed with a function handle (see this related answer).

The error you are getting is because you can't call o and use it as an input to fminsearch() since o is undefined. To get o, you have to first get u(x,y), plus as mentioned, fminsearch requires a function handle as an input.

You have several options that still use your standalone function, u(x,y).

1. Create a function handle
Define a function handle that calls u(x,y) but has a single argument which is a 2 x 1 vector, z = [x; y].

fh =@(z) u(z(1),z(2));
z0 = [1; 2];                         % Initial Guess for z = [x; y]
[z,TC] = fminsearch(fh,z0)     

2. Change the function and call it directly

The same result is possible with

[z,TC] = fminsearch(@u,z0)

if you redefine u(x,y) to be as follows:

function o=u(z) 
   x = z(1);
   y = z(2); 
   % your function code here
end

Upvotes: 1

Related Questions