maephisto
maephisto

Reputation: 5182

Minimization of a three variables function in Matlab

I'm trying to use an example of minimizing functions, given in Matlab docs and run it in Matlab R2016a but it yields an error. Here's the example: enter image description here

This is the code I wrote based on that:

function b = test_algo(v)
x = v(1);
y = v(2);
z = v(3);
b = x.^2 + 2.5*sin(y) - z^2*x^2*y^2;

v = [-0.6 -1.2 0.135];
a = fminsearch(@test_algo,v);

disp('a', a);

But instead of expected result i get an error:

Not enough input arguments.

Error in test_algo (line 3)
x = v(1);

Any idea why? Thanks!

Upvotes: 0

Views: 542

Answers (2)

edwinksl
edwinksl

Reputation: 7093

You need to define the objective function test_algo separately from the code that calls it. Since you don't need much code to define your objective function, you can use an anonymous function to define it:

b = @(v) v(1).^2 + 2.5*sin(v(2)) - v(3)^2*v(1)^2*v(2)^2;
v0 = [-0.6 -1.2 0.135];
a = fminsearch(b,v0);
disp(a);

Upvotes: 0

bushmills
bushmills

Reputation: 673

Depending on how you execute your code, you have to put the call of fminsearch in a separate function:

function test()

v = [-0.6 -1.2 0.135];
a = fminsearch(@test_algo,v);

disp(a);

function b = test_algo(v)
x = v(1);
y = v(2);
z = v(3);
b = x.^2 + 2.5*sin(y) - z^2*x^2*y^2;

The above sample works for me, if I put everything in a m-file and execute it.

Upvotes: 2

Related Questions