How do I add anonymous functions together?
4 views (last 30 days)
Show older comments
What I would like to achieve is a for loop with n iterations that lengthens a function after each iteration, but I'm not sure what the syntax is to add two anonyous functions
Sample code:
for n = 1 : iterations
function = function + new_function
end
where 'function' and 'new_function' are anonymous functions
Desired output:
if function = @(x) x.^2
and new_function = @(x) x.^3
function + new_function = x.^2 + x.^3
0 Comments
Accepted Answer
Matt J
on 26 Aug 2022
Edited: Matt J
on 26 Aug 2022
I was hoping for something along these lines:
for n = 0:5
new_func = @(x) (((-1)^n).*((x).^(2*n)))./(factorial(2*n))
final_func = @(x) final_func(x) + new_func(x)
end
After the for loop, I'd like to output to look smiliar to this:
final_func = @(x) (((-1)^0).*((x).^(2*0)))./(factorial(2*0)) + (((-1)^1).*((x).^(2*1)))./(factorial(2*1)) + (((-1)^2).*((x).^(2*2)))./(factorial(2*2));
No, not without string manipulation.
The function generated by your loop will return the correct values (and is equivalent to @Stephen23's answer), but it is grossly inefficient. You could get to a much better implementation of final_func in one line by using vectorization.
n=0:5;
final_func=@(x) sum( (((-1).^n).*((x).^(2*n)))./(factorial(2*n)) );
More Answers (1)
Matt J
on 26 Aug 2022
Edited: Matt J
on 26 Aug 2022
Trying to sum/concatenate anonymous functions is a bad thing to do, in general. Here is one way to accomplish it, however,
fstr=@(z) string( extractAfter(func2str(z),'@(x)') );
func="";
for n = 1 : iterations
func= func + fstr(new_function);
end
func=str2func( "@(x)"+func )
2 Comments
Stephen23
on 26 Aug 2022
Edited: Stephen23
on 26 Aug 2022
" I'd like to output to look smiliar to this: final_func = @(x) (((-1)^0).*((x).^(2*0)))./(factorial(2*0)) + (((-1)^1).*((x).^(2*1)))./(factorial(2*1)) + (((-1)^2).*((x).^(2*2)))./(factorial(2*2));"
Adding functions is a red-herring. You should be using arrays, not adding functions in a loop.
See Also
Categories
Find more on Loops and Conditional Statements 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!
