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

조회 수: 1 (최근 30일)
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
dpb
dpb 2019년 10월 13일
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...

댓글을 달려면 로그인하십시오.

채택된 답변

Fabio Freschi
Fabio Freschi 2019년 10월 13일
편집: Fabio Freschi 2019년 10월 13일
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
Fabio Freschi
Fabio Freschi 2019년 10월 15일
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.
Yuechuan Chen
Yuechuan Chen 2019년 10월 15일
I'm grateful for the help, thank you for the explanation!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Matt J
Matt J 2019년 10월 15일
편집: Matt J 2019년 10월 15일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by