How to use fzero in a loop to obtain the first 3 positve solutions for cos3x=sin3x?

1 view (last 30 days)
As it says in the title, I can't figure a way to do it. I've tried for loops but it didn't quite work.
Thanks!
  1 Comment
dpb
dpb on 13 Oct 2019
Well, let's see what you tried...seems straightforward enough although you'll have to give starting values to make fzero find the desired solutions...

Sign in to comment.

Accepted Answer

Fabio Freschi
Fabio Freschi on 13 Oct 2019
Edited: Fabio Freschi on 13 Oct 2019
fzero gives you only one solution. In case of multiple roots, the choice depends on the initial choice and on the algorithm. If you plot cos(3*x)-sin(3*x), you can see that the first 3 solutions are in the interval [0,pi]. So you can loop over x with a small step and then remove the duplicated solutions
% your function
f = @(x)cos(3*x)-sin(3*x);
% picture
figure, hold on
fplot(f,[0,pi]);
% number of divisions
N = 100;
% initial guesses
x0 = linspace(0,pi,N);
% preallocation
xSol = zeros(N,1);
% set tolerance
tol = 1e-4;
options = optimset('TolX',tol);
% now loop over x
for i = 1:N
xSol(i) = fzero(f,x0(i),options);
end
% filter repeated solutions
xSolUnique = uniquetol(xSol,10*tol);
% filter solution out of bounds
xSolUnique = xSolUnique(xSolUnique > 0 & xSolUnique < pi)
% add solutions to the plot
plot(xSolUnique,f(xSolUnique),'o');
  3 Comments
Fabio Freschi
Fabio Freschi on 15 Oct 2019
My pleasure!
Basically, I created a set of uniformly distributed points between 0 and pi and sotred them in x0.
The I ran fzero starting from each of these points with the loop. Because some initial starting point may provide the same root, I removed the duplicated solution with uniquetol (the final solutions may differ of the tolerance used by fzero). I finally removed the solution that fell out of the domain 0-pi.
If the solution answer your original problem and you are satisfied, please accept it.

Sign in to comment.

More Answers (1)

Matt J
Matt J on 15 Oct 2019
Edited: Matt J on 15 Oct 2019
It seems like a strange homework problem, since it is so easily solved analytically. Well, assuming we play dumb to that, you need to use some analysis to find what intervals the first 3 solutions lie in. The equation is equivalent to tan3x=1 and so you know the solutions lie in the open intervals (0,pi/6),(pi/6,3*pi/6), and (3*pi/6,5*pi/6). You can then use fzero to search for roots in these intervals, e.g.,
>> fun=@(x) tan(3*x)-1;
>> x2=fzero(fun,[pi/6+eps,3*pi/6-eps])
x2 =
1.3090
and similarly for the other solutions.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!