Problem defining anonymous functions with multiple inputs

2 views (last 30 days)
Hi all, I have a problem defining anonymous functions with multiple inputs. It keeps saying:
Error using tpsmain>@(thetaest,aest)sum(-n.*log(exp(-(x-aest-thetaest/2).^2/2)+exp(-(x-aest+thetaest/2).^2/2))) (line 41) Not enough input arguments.
The relevant portion of the code is:
f=@(thetaest,aest) sum(-n.*log(exp(-(x-aest-thetaest/2).^2/2)+exp(-(x-aest+thetaest/2).^2/2)));
options = optimset('MaxFunEvals',3000,'MaxIter',3000,...
'GradObj','off','Hessian','off',...
'TolX',1e-5,'TolFun',1e-20,...
'DerivativeCheck','off','Diagnostics','off',...
'Display','off');
mu = fmincon(f,0,[],[],[],[],0,3,[],options);
What am I doing wrong? Any help would be greatly appreciated, thank you very much!
Edit: Sorry I forgot to mention, n and x are defined above as
x = -5:0.01:5
lambda1 = exp(-(x-a(floor(atrue*100+1))-theta(floor(thetatrue*100+1))/2).^2/2);
lambda2 = exp(-(x-a(floor(atrue*100+1))+theta(floor(thetatrue*100+1))/2).^2/2);
n = poissrnd((lambda1+lambda2)*dx);
atrue and thetatrue are the iterations of a for-loop.

Answers (2)

ANKUR KUMAR
ANKUR KUMAR on 29 Oct 2017
You have not defined 'n' and 'x' variable in the list of inputs in the function. Try using this
function [ a ] = my_function( n,x,thetaest,aest )
a=sum(-n.*log(exp(-(x-aest-thetaest/2).^2/2)+exp(-(x-aest+thetaest/2).^2/2)));
end
Now, If u want type in command window
my_function(2,2,2,5)
You will get you desired answer.
You should to list out all input variables in the bracket, in the first line after writing the function name.
  1 Comment
Kenneth Ng
Kenneth Ng on 29 Oct 2017
sorry I forgot to mention they are all defined, updated the question as to how they are defined. Thank you!

Sign in to comment.


Star Strider
Star Strider on 29 Oct 2017
From the fmincon documentation for the fun (link) argument:
  • Function to minimize, specified as a function handle or function name. fun is a function that accepts a vector or array x and returns a real scalar f, the objective function evaluated at x.
So you either need to give fmincon:
mu = fmincon( @(thetaest) f=@(thetaest,aest), ...
or:
mu = fmincon( @(x) f(x(1), x(2)), ...
or something similar so that it has a vector or array argument.
NOTE This is UNTESTED CODE. It should work.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!