How can I pass a anonymous function as an output to another function?

조회 수: 1 (최근 30일)
function [a0,a1,a2]= fcn(s,v,a,T)
%a0,a1,a2 are coefficients of a polynomial which are calculated based on inputs s,v,a,T
end
The above function returns coefficients. The polynomial g(t) needs be calculated at time t =T , based on equation g(t) = a0 + a1* t^2+ a2* t^3.
for doing this I have added the following lines to the function above
function [a0,a1,a2]= fcn(s,v,a,T)
%a0,a1,a2 are coefficients of a polynomial which are calculated based on inputs s,v,a,T
g = @(T)
a2*T^2 + a1*T + a0
g(T)
end
But I am unable to pass g(t) as output to the function fcn as shown below:
function [a0,a1,a2,g(t)]= fcn(s,v,a,T)
%a0,a1,a2 are coefficients of a polynomial which are calculated based on inputs s,v,a,T
g = @(T)
a2*T^2 + a1*T + a0
g(T)
end
Looks likes I am not allowed to do that . I would like to know how this can be achieved
Note: If I just use g in the output array, it doesn't return the g(T) value instead it returns a2*T^2 + a1*T + a0 because g is a function handle.

채택된 답변

Stephen23
Stephen23 2020년 9월 17일
편집: Stephen23 2020년 9월 17일
"Looks likes I am not allowed to do that . I would like to know how this can be achieved"
Your attempted code has several bugs in it, e.g.:
  • g(t) is not a valid output argument.
  • g = @(T) is not a valid anonymous function.
  • you do not define the output arguments a0,a1,a2.
  • a2*T^2 + a1*T + a0 is not assigned to anything, so its result is discarded.
  • a2*T^2 + a1*T + a0 is not "...based on equation g(t) = a0 + a1* t^2+ a2* t^3."
  • probably others, I gave up checking at that point.
A function handle is a variable just like any other, it can be returned just like any other variable, e.g.
function out = myfun()
out = @sin;
end
and tested:
>> f = myfun();
>> f(pi/2)
ans = 1
"The polynomial g(t) needs be calculated at time t =T , based on equation g(t) = a0 + a1* t^2+ a2* t^3."
For that you do not need to return a function handle. you can just calculate the value directly and return that:
function g = fcn(s,v,a,t)
a0 = ..;
a1 = ..;
a2 = ..;
g = a0 + a1.*t.^2+ a2.*t.^3;
end

추가 답변 (0개)

카테고리

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