0

I try to find all the roots of the function f=(x^3)*cos(x) between -6pi and 6pi using fzero.

I create a function:

function y3=f(x)
  f=(x^3)*cos(x);
end

% Then at the command window:

syms x;
fun=@f
x1=-6*pi;
x2=-5*pi;
r=zeros(1,12);
for i=1:12
  x=fzero(@fun,[x1 x2]);
  r(i)=x;
  x1=x1+pi;
  x2=x2+pi;
end

I got this error:

Error: "fun" was previously used as a variable, conflicting with its use here as the name of a function
or command. See "How MATLAB Recognizes Command Syntax" in the MATLAB documentation for details.

How can I solve it? Thank you

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
  • Your function body should be `y3=(x^3)*cos(x);` instead of `f=(x^3)*cos(x);` – Patrick Roberts Jan 31 '18 at 20:05
  • 1
    You write `fun=@f`, and later `@fun`. In this second statement, you are treating `fun` as a function, but it's declared as a variable by your first statement. The solution is to write `fzero(fun,...)` or `fzero(@f,...)`. – Cris Luengo Jan 31 '18 at 20:06

1 Answers1

0

I think I have an answer for you. According to the fzero documentation on the fun input to fzero, you can directly input an anonymous function. Hence you can do something like this:

clc; clear;

x1=-6*pi;
x2=-5*pi;

r=zeros(1,12);

for i=1:12
    x=fzero(@(x) (x.^3)*cos(x),[x1 x2]);

    r(i)=x;

    x1=x1+pi;    
    x2=x2+pi;    
end
r

This gave an output of:

r =

-17.2788  -14.1372  -10.9956   -7.8540   -4.7124         0         0    4.7124    7.8540   10.9956   14.1372   17.2788
natemcintosh
  • 730
  • 6
  • 16