Problem defining anonymous functions with multiple inputs
2 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(2 个)
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.
Star Strider
2017-10-29
- 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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!