1
votes

I am trying to optimize the function using fminsearch and function handle

but, I get the error A and B must be floating point scalars. In detalis,

Error using integral (line 86) A and B must be floating point scalars.

Error in @(x,p)(integral(@(n)((p(1)-p(2))*exp(n)),-inf,x+3))

Error in @(x)((x-f2(x,p)).^2)

Error in integralCalc/iterateScalarValued (line 314) fx = FUN(t);

Error in integralCalc/vadapt (line 133) [q,errbnd] = iterateScalarValued(u,tinterval,pathlen);

Error in integralCalc (line 76) [q,errbnd] = vadapt(@AtoBInvTransform,interval);

Error in integral (line 89) Q = integralCalc(fun,a,b,opstruct);

Error in @(p)(integral(@(x)((x-f2(x,p)).^2),-3,3))

Error in fminsearch (line 191) fv(:,1) = funfcn(x,varargin{:});

How can I solve this?

i think x-3 become a problem but i cannot deal with it. x should be variable in f2 in order to do integral with respect to x in q3

Thank you in advance

sigma=0.1;

f2=@(x,p)(integral(@(n)((p(1)-p(2))*exp(n)),-inf,x+3));

q3=@(p)(integral(@(x)((x-f2(x,p)).^2),-3,3));

[p, fval] = fminsearch(q3,[0.1 0.4]);
1
Welcome to stackoverflow J.Lee. It's helpful to tag your problem with the programming language you're using -- I added "matlab" which is what this looks like, and removed "floating" which is a tag used for floating divs and whatnot in css. - Paul Hankin
For the sake of debugging, try writing out your code as full functions, instead of function handles. Then, matlab will tell you more useful information about where the error is happening (like line numbers). - user20160
Can you provide a p and n? If they are large, please post only enough to recreate your problem. - Stewie Griffin
CAn yuo also copy paste the whole stack of errors? - Ander Biguri
Thank you, i copied patste the whole stack of errors - J.Lee

1 Answers

0
votes

The problem is that when you integrate over x, the function "integrate" gives f2 a vector to evaluate. Which is the same reason you use the dot notation in the function "q3".

The quick fix is to use arrayfun around the "f2" - but you should really consider to adapt to what user20160 suggested in the comments, namely to make full functions, then it will be easier to debug and as it takes in a vector, you can make a for loop, which runs over the inputted endpoints. Standard for-loops are faster than standard arrayfun.