Polynomial with nested and anonymous functions.

6 ビュー (過去 30 日間)
Wai Han
Wai Han 2020 年 10 月 22 日
コメント済み: Senal Direcksze 2021 年 2 月 11 日
How can I write this polynomial function without loops?
function fh = get_polynomial_handle(p)
function polynomial = poly(x)
polynomial = 0;
for i = 1 : length(p)
polynomial = polynomial + p(i) .* x.^(i-1);
end
end
fh = @poly;
end
% I try to make this function recursively, but anyway, I am having some errors in writting this function without loop.
% Can anyone explain me?
% Note: The function is not necessary to be recursive, it's just one of the ways I've thought of.

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 10 月 22 日
Something like this
polynomial = sum(p .* x.^(0:numel(p)-1));
Also see polyval().
  3 件のコメント
Ameer Hamza
Ameer Hamza 2020 年 10 月 23 日
I am glad to be of help!
Senal Direcksze
Senal Direcksze 2021 年 2 月 11 日
Thanks a lot mn. You just made my day, was stuck in this question for quite a while since yesterday. I was at 2 out of 3 errors. Even posted a forum to my lecturer for the first time last night.
P.S I tried with length & recursion but kept getting bugs for atleast one or 2 errors. Either some inputs didnt work properly or out of memory.
function pf = poly_fun(p)
if nargin < 1%Check no.of inputs
return;
end
function polynomial = poly(x)
polynomial = sum(p .* x.^(0:numel(p)-1));%numel for polynomial exponential
end
pf = @poly;
end

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by