Polynomial with function handle.
38 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
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
0 个评论
更多回答(2 个)
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
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
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Polynomials 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!