Cannot use fzero on a previously defined function. Am I doing something wrong?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Diego Arana
le 11 Oct 2015
Commenté : Diego Arana
le 12 Oct 2015
I'm having trouble using fzero on this function:
function out = f(theta)
L1 = 2; L2 = sqrt(2); L3 = sqrt(2);
g = pi/2;
p1 = sqrt(5); p2 = sqrt(5); p3 = sqrt(5);
x1 = 4; x2 = 0; y2 = 4;
A2 = L3*cos(theta) - x1;
B2 = L3*sin(theta);
A3 = L2*cos(theta + g) - x2;
B3 = L2*sin(theta + g) - y2;
D = 2*(A2*B3 - B2*A3);
N1 = B3*(p2^2 - p1^2 - A2^2 - B2^2) - B2*(p3^2 - p1^2 - A3^2 - B3^2);
N2 =-A3*(p2^2 - p1^2 - A2^2 - B2^2) + A2*(p3^2 - p1^2 - A3^2 - B3^2);
out = N1^2 + N2^2 - (p1^2)*(D^2);
What I'm doing is inputting this in the command window:
>> fzero(f,-1)
I have saved the function in an m-file as 'f.m'. And I'm obtening the following error:
Not enough input arguments.
Error in f (line 8)
A2 = L3*cos(theta) - x1;
Am I doing something wrong? I will attach the m-file just in case.
0 commentaires
Réponse acceptée
John D'Errico
le 11 Oct 2015
Modifié(e) : John D'Errico
le 11 Oct 2015
Yes. You are doing something wrong. Admittedly, others have made the same mistake. It comes down to understanding how MATLAB looks at a line of code to be executed.
See that this works:
fzero(@f,-1)
ans =
-0.7854
And it fails here:
fzero(f,-1)
Not enough input arguments.
Error in f (line 6)
A2 = L3*cos(theta) - x1;
Why? Because in the first case, I explicitly told MATLAB that f was a function to be passed in.
As you have tried to call fzero, see what happened. When you try to execute the expression fzero(f,-1), MATLAB see the f, and tries to evaluate the function f. MATLAB does not see the outer call to fzero and realize what you want it to do. MATLAB is very literal. It does exactly as you tell it. MATLAB sees f, and says it must evaluate a function with no inputs, but the function f has an input argument. Ergo, the error message.
Finally, had you done this, it would also have worked.
fzero('f',-1)
ans =
-0.7854
Here MATLAB recognizes that you passed in a string argument, so it assumes that to be the name of the function.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Variables dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!