How do I add anonymous functions together?
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
Matt J
am 26 Aug. 2022
Bearbeitet: Matt J
am 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)) );
Weitere Antworten (1)
Matt J
am 26 Aug. 2022
Bearbeitet: Matt J
am 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 Kommentare
Stephen23
am 26 Aug. 2022
Bearbeitet: Stephen23
am 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.
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

