How can I vectorize this code that uses the fzero function?

1 回表示 (過去 30 日間)
Martin Schwesinger
Martin Schwesinger 2015 年 8 月 3 日
コメント済み: Star Strider 2015 年 8 月 3 日
Hello,
I have the following code:
precision = 1000;
E = zeros(1,precision);
ecc = 0.3;
for k = 1:precision
M = 2*pi*k/precision;
E(k) = fzero(@(x) anomaly(x,M,ecc),M)
end
-----
function y = anomaly(x,M,ecc)
y = x - ecc*sin(x) - M;
end
Is there a way to vectorize this code and get rid of the k-loop? The fzero function doesn't accept a vector argument.

採用された回答

Star Strider
Star Strider 2015 年 8 月 3 日
That is likely as efficient as you can write code to calculate several zeros using fzero. You have to specify an initial estimate of the zero, and that apparently changes in your loop. I plotted ‘E’, and it is not linear, so your code is likely optimal.
  2 件のコメント
Martin Schwesinger
Martin Schwesinger 2015 年 8 月 3 日
Thanks for the answer! The initial estimate can be set to a fixed value, should that allows us to vectorize the code (trade-off more time searching for the zero vs. less time looping). Did you imply that this was what was preventing the code from being further optimized?
Star Strider
Star Strider 2015 年 8 月 3 日
My pleasure!
I apologise for the delay — life intrudes.
You would have to estimate the zero-crossing in each interval of ‘M’ regardless. The fzero call is likely as efficient as you can get, because your function is nonlinear and a reasonably precise estimate of ‘E’ with it is likely as good as you can get.
You might even calculate fewer values of ‘E’ in your loop, and then use interp1 for reasonably precise interpolation of ‘E’ at specific values of ‘M’.
It all depends on the rest of your code, and what you want to do.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeInterpolation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by