简体   繁体   English

在父函数的输入之外创建函数句柄?

[英]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. 我正在尝试制作一个接受x函数的函数(例如x ^ 2 + 5x + 2),并使用该输入来创建函数句柄。 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. 我认为问题仅在于我不知道所有不同的函数类型是什么,而且我不明白如何正确地“连接”“ @(x)”和输入函数以构成函数句柄。

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. 它说input1的类型为double,即使只是一个字母也是如此。

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 : 最后的想法:使用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) str2func ,(感谢Luis str2func

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

Either way it's not too pretty, hence my suggestion to just pass a handle. 无论哪种方式都不太漂亮,因此我建议仅传递一个手柄。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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