필터 지우기
필터 지우기

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 CenterFile Exchange에서 Polynomials에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by