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

2 views (last 30 days)
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.

Accepted Answer

Stephen23
Stephen23 on 17 Sep 2020
Edited: Stephen23 on 17 Sep 2020
"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

More Answers (0)

Categories

Find more on Polynomials in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!