Taking in a function as an argument
Show older comments
I'm trying to make a function which takes in a function and then uses it. Right now my code looks like this:
function out = func(inputfunc, constant1, constant2)
inputfuncval1 = inputfunc(constant1);
...code...
end
When I then try to call it with a function like this:
out = func(@(x) testfunc(x),x1 ,x2);
It interpretets my input as an array instead of a function.
Anyone got any ideas on how to solve this issue?
2 Comments
Guillaume
on 8 Nov 2019
Can you give us the full text of the error you see. The code you show should work although
out = func(@testfunc, x1, x2);
would be simpler.
Jakob Grunditz
on 8 Nov 2019
Accepted Answer
More Answers (1)
M
on 8 Nov 2019
How is testfunc defined ?
Here is a simple working example:
function out = func(inputfunc, constant1, constant2)
out = inputfunc(constant1, constant2);
end
out = func(@(x,y) x+y,1,2)
out =
3
2 Comments
Jakob Grunditz
on 8 Nov 2019
Guillaume
on 8 Nov 2019
As I commented in your question, if the above doesn't work, give us the full text of the error message.
With the following function:
function out = func(inputfunc, constant1, constant2)
out(1) = inputfunc(constant1);
out(2) = inputfunc(constant2);
end
I get:
>> out = func(@(x) exp(x)+x^2-1, 1, 2)
out =
2.71828182845905 10.3890560989307
No problem there.
Categories
Find more on Surface and Mesh Plots 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!