# How to pass summation of function handles to fminsearch

10 views (last 30 days)

Show older comments

Hi, everyone

I am trying to pass a sum of function handles to fminsearch, however it always give me the error: Not enough input arguments. Error in @(i,x)sum(fun(2:3,x)) Error in fminsearch (line 200) fv(:,1) = funfcn(x,varargin{:});

Here is the simplified version of my code:

fun = @(x,i)100*(x(2) - x(1)^2)^2 + (i - x(1))^2;

sum_A=@(i,x) sum(fun(2:3,x)); // I have to do this summation in my real code

x0 = [-1.2,1];

x = fminsearch(sum_A,x0);

Why does it aways throw me an error that Not enough input arguments? In fact, sum_A just has 2 variables, what is problem here?

Any help is greatly appreciated! Thank you very much

##### 0 Comments

### Accepted Answer

John BG
on 20 Mar 2017

ok,

it's all about making fminsearch work with the 2 input function as defined, right?

define the 2nd vector in advance the same way that you have defined x

s=[1 2 3];x=[3 4 5]

x0=[-1,2 1] % initial for fminsearch

this works

f = @(x,c) x(1).^2+c.*x(2).^2;

c = [1.5 2];

fminsearch(@(x) f(x,c(1)),[0.3;1])

=

1.0e-04 *

-0.244731948340174

0.315866965061825

.

and this works too

f = @(x,c) x(1).^2+c(1).*x(2).^2; % The parameterized function.

c = [1.5 2]; % The parameter.

fminsearch(@(x) f(x,c(1)),[0.3;1])

= 1.0e-04 * -0.244731948340174 0.315866965061825

and this works too

f = @(x,c) (x(1).^2+c(1)).*x(2).^2; % The parameterized function.

c = [1.5 2]; % The parameter.

fminsearch(@(x) f(x,c),[0.3;1])

.

If you manage in any of these ways, would you please consider marking my answer as accepted answer?

thanks for attention

John BG

##### 0 Comments

### More Answers (3)

Darshit Mehta
on 16 Mar 2017

John BG
on 16 Mar 2017

Hi Albert

1.

I have changed the syntax so it doesn't return error, could you please be so kind to confirm that this way is how you need to further process your data?

fun = @(x,i) 100*(x(2)-x(1)^2)^2+(i- x(1))^2;

% MATLAB comment // I have to do this summation in my real code

x0 = [-1.2,1];

N=10

sum_A=0

for k=1:1:N

sum_A=sum_A+fun(x0,k)

end

2. I don't know if the following is what you need for the fminsearch, again I make it avoid error, please confirm it me be of use in your code

ni=[-10:.01:10]

fun2= @(x,s) 100*(x(2)-x(1)^2)^2+(s- x(1))^2;

for s=1:1:numel(ni)

xmin = fminsearch(@(x) fun2(x,ni(s)),x0);

end

if you find this answer useful would you please be so kind to mark my answer as Accepted Answer?

To any other reader, please if you find this answer

please click on the thumbs-up vote link

thanks in advance

John BG

### See Also

### Categories

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!