Reputation: 11
I need to know the minimum of the curve y= sin(r)+r.^2
using fzero
.
I created a function:
function w=myfun(r)
w=diff(sin(r)+r.^2);
end
Then at the command window:
r=[-pi:.01:pi];
fzero( @myfun,0)
But there is always an error:
Operands to the
||
and&&
operators must be convertible to logical scalar values.Error in
fzero
(line 327)
elseif ~isfinite(fx) || ~isreal(fx)
fzero(@myfun,0)
What should I do?
Upvotes: 1
Views: 309
Reputation: 3052
As stated by Cris, you cannot use diff, as it finds the difference between neighbouring points (with one value, this difference is undefined.).
Instead, you can do one of the following
Take the derivative yourself:
function w=myfun(r)
w=cos(r)+2*r;
end
Do a numerical differentiation
function dw=myfun(r)
h = sqrt(eps);
wh=(sin(r+h)+(r+h).^2;
w= (sin(r)+(r).^2;
dw = (wh - w)/(h);
end
Alternatively, use a numerical minimizer
w= @(r) (sin(r)+(r).^2;
xmin = fminsearch(w,0);
Upvotes: 1
Reputation: 60494
diff
computed the finite difference derivative (i.e. the difference between neighbors). Here, r
is scalar, so diff
returns an empty array.
You will need to define your function myfun
such that it returns the derivative given a single value. So you will have to manually compute the derivative function and write that into myfun
.
Upvotes: 1