Problem defining anonymous functions with multiple inputs

조회 수: 2 (최근 30일)
Kenneth Ng
Kenneth Ng 2017년 10월 29일
답변: Star Strider 2017년 10월 29일
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.

답변 (2개)

ANKUR KUMAR
ANKUR KUMAR 2017년 10월 29일
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
Kenneth Ng
Kenneth Ng 2017년 10월 29일
sorry I forgot to mention they are all defined, updated the question as to how they are defined. Thank you!

댓글을 달려면 로그인하십시오.


Star Strider
Star Strider 2017년 10월 29일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by