problem with fzero in my code

fzero won´t work, anyone knows what may be the problem?
Skärmavbild 2019-10-14 kl. 08.29.30.png

Answers (2)

your fun is neither acceppting nor using inputs
You should write the symbolic function like this
fun = @(x)cos(x);
x0 = fzero(fun,0.5);

8 Comments

your fun is neither acceppting nor using inputs
We do not know that. We see @cosx which is a handle to a function that takes a number of inputs that is not known to us because we do not have the source code for it.
fun = @(x)cos(x);
You can also just use
fun = @cos;
This takes the same number of inputs that cos takes. It is not an error to take the handle of a function and pass that to fzero.
I changed my code but it srill won´t work, the same error message comes up and I do not get an answer for fzero
Skärmavbild 2019-10-14 kl. 08.50.10.png
Mathworks does not define any function named xcos or cosx . What would you expect those functions to calculate if they existed ?
@Walter: you are right. I assumed the function was cos(x) from the plot a few lines before. If it is not the case, the OP can clarify what he/she wants to do.
@Hanna: what's wrong in the code I posted. It seems to work on my pc
>> fun = @(x)cos(x);
>> tic; x0 = fzero(fun,0.5); toc
Elapsed time is 0.004853 seconds.
The error you posted is saying that function xcos does not exist. What is the analytic expression of the function you are supplying to fzero? If you want the roots of x*cos(x), you should specify this in the definition of anonymous function, e.g.
fun = @(x)x*cos(x);
% ^ ^ \______/
% | | your function
% | input argument, to be used in the function definition
% handle to the function
The task is to find the roots to the function y = cosx in the interval -pi, 2pi.
THen you would use the code that Fabio showed, but with a number of different starting points to get the various roots.
It is not clear why your comments start talking about xsinx when you want to find roots of cosx
I am also going to find how many tangents lines that goes torugh the origin for cosx and that is why I talk abot xsinx in my comments.
I do not understand what tangent lines through the origin for cosx has to do with xsinx ? Tangent lines to cosx would have to do with sinx not xsinx .

Sign in to comment.

Create a function file and save it to the same dierctory as
function y = f(x)
y = cos(x);
end
Then use this function in the section of your script as
%%
fun = @f; % function
x0 = 0.5; % initial point
ff = fzero(fun,x0);

Asked:

on 14 Oct 2019

Commented:

on 15 Oct 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!