Polynomial with function handle.

72 ビュー (過去 30 日間)
Ahsan Ali
Ahsan Ali 2020 年 10 月 31 日
コメント済み: Walter Roberson 2020 年 12 月 23 日
Remember the example from the video that showed how to return a function handle to a nested function that computed the value of a polynomial? Here it is:
function fh = get_polynomial_handle(p)
function polynomial = poly(x)
polynomial = 0;
for ii = 1:length(p)
polynomial = polynomial + p(ii) .* x.^(ii-1);
end
end
fh = @poly;
end
It takes a vector of coefficients p, defines a function that returns the value of the polynomial given the scalar input x, and returns a function handle to it. Here is an example run:
>> p = get_polynomial_handle(1:5)
p =
function_handle with value:
@get_polynomial_handle/poly
>> p(1)
ans =
15
Your task is simple: modify the code above so that it does not use any loops.
Here is the code, i tried;
function fh = get_polynomial_handle(p)
function fn = poly1(x)
ii = 1:length(p);
fn=poly(ii);
function polynomial = poly(ii)
if ii==1
polynomial= p(1);
else
polynomial = p(ii).*x.^(ii-1)+ poly(x,ii-1);
end
end
end
fh = @poly1;
end
Commond window error.
>> p = get_polynomial_handle([1:5])
p =
function_handle with value:
@get_polynomial_handle/poly1
>> p(1)
Error using get_polynomial_handle/poly1/poly
Too many input arguments.
Error in get_polynomial_handle/poly1/poly (line 9)
polynomial = p(ii).*x.^(ii-1)+ poly(x,ii-1);
Error in get_polynomial_handle/poly1 (line 4)
fn=poly(ii);
I can not able to figure out, what is wrong in this code. Please help!

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 10 月 31 日
You defined the nested poly() function with this signature
function polynomial = poly(ii); % single input
But then you are calling it like this
poly(x,ii-1); % two inputs
Also, the task only requires you not to use for-loop. It does not say to do it with recursion. Following is a more intuitive loop-free approach.
function fh = get_polynomial_handle(p)
function polynomial = poly(x)
polynomial = sum(p.*x.^(0:numel(p)-1));
end
fh = @poly;
end

その他の回答 (2 件)

ABHIJIT BISWAS
ABHIJIT BISWAS 2020 年 12 月 23 日
function fh = poly_fun(p)
function polynomial = poly(x)
polynomial = sum(p.*x.^(0:numel(p)-1));
end
fh = @poly;
end
  1 件のコメント
Walter Roberson
Walter Roberson 2020 年 12 月 23 日
what difference is there between this and the existing https://www.mathworks.com/matlabcentral/answers/632149-polynomial-with-function-handle#answer_529929

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


Bruno Luong
Bruno Luong 2020 年 10 月 31 日
function fh = get_polynomial_handle(p)
function fn = poly1(x)
fn=poly(p);
function polynomial = poly(p)
n = length(p);
if n==0
polynomial=0;
else
polynomial = p(1).*x.^(n-1) + poly(p(2:end));
end
end
end
fh = @poly1;
end

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by