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!