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
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
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
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.
更多回答(1 个)
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 Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!