Error using fzero " FUN must be a function, a valid string expression, or an inline function object"
24 views (last 30 days)
I am getting errors while using fsolve or fzero in the following code:
U = 1;
while U < 20
eq = @(q) 2.*(1-cos(2.*pi.*q));
hq = @(q,n0) ((eq(q)).^2+2.*U.*n0.*(eq(q))).^0.5;
y = @(q,n0) (((eq(q))+(U.*n0))./hq(q,n0))-1;
a = -0.5;
c = -0.01;
v = @(n0) (integral(@(q) y(q,n0),a,c));
cv =@(n0) n0+(0.5*v(n0))-1;
n0 = fzero(cv(n0),0.1);
U = U + 1;
Can anyone please help me out?
More Answers (1)
John D'Errico on 25 Feb 2015
Edited: John D'Errico on 25 Feb 2015
cv is a function handle, i.e., perfectly valid for fzero to work on. It is a function that takes one argument, and returns an output that can be minimized.
cv(n0) is a variable. A number. Well, it would be, if n0 was defined. It may be so in your workspace, as otherwise, you would have gotten a different error before fzero was even entered.
Regardless, cv(n0) is NOT one of the valid things fzero can minimize.
There IS a difference. While you may THINK of cv as being a function of n0, when MATLAB sees the expression cv(n0), it looks around and says to itself, yep, I found n0. I found cv. It will evaluate that expression, then pass it in as an argument to a function called fzero.
Only then does fzero take control. It sees what was passed in, in this case, the variable that contains the result of cv(n0), where again, n0 MUST have been defined in your workspace, else you would have gotten a different error. That value is indeed NOT a function. Just a number. So fzero gets upset and tells you:
" FUN must be a function, a valid string expression, or an inline function object"
So the solution is simple. Remove the (n0) in your calls to fzero or to fsolve, like this:
n0 = fzero(cv,0.1);