简体   繁体   中英

Creating a function handle out of the input of the parent function?

forgive me if the answer is this is terribly obvious or if there's a much better way to do this.

I'm trying to make a function that accepts a function of x (eg x^2 + 5x + 2), and use that input to create a function handle. That way I can use that function for whatever else I need it to do.

I think the problem is just that I don't know what all the different function types are, and I don't understand how to "concatenate" the "@(x)" and the input function correctly to make the function handle.

Here's what I tried:

function test(input1)

function_1 = @(x) + input1

end

It says that input1 is of type double, even if it's just a letter.

And if I try to enter the input as a string and convert it to symbolic data, I just get an array of numbers for the concatentaion.

Any help would be greatly appreciated, thanks.

Passing a string probably won't get you what you want, or it will get ugly.

This might be off topic, but it's important to understand that anonymous functions store the value of non-input variables at the time of creation. Any values that you want to change on each call to the function need to be input arguments.

>> a = pi;
>> fun = @(x) x * a;
>> fun(2)
ans =

    6.2832

You can see the stored values as follows,

>> fi = functions(fun)
fi = 
     function: '@(x)x*a'
         type: 'anonymous'
         file: ''
    workspace: {[1x1 struct]}
>> fi.workspace{1}
ans = 
    a: 3.1416

If your intention is to have another input argument, just have two input arguments:

>> fun = @(x,y) x * y;
>> fun(2,pi)
ans =
    6.2832

However, you can pass a function handle to a function, and then call it. Perhaps this is what you're after:

function myfun = funTester(fh,x)
% presumably do something useful here
myfun = fh(x);

end

For example,

>> fun = @(x) x.^2 + 5*x + 2
fun = 
    @(x)x.^2+5*x+2
>> funTester(fun,-2)
ans =
    -4

Final thought: Construct a handle with eval :

>> expression  = 'x^2 + 5*x + 2';
>> eval(['h = @(x) ' expression])  % put this in your function
h = 
    @(x)x^2+5*x+2

Or str2func , (thanks Luis Mendo)

h = str2func(['@(x)' expression])

Either way it's not too pretty, hence my suggestion to just pass a handle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM