Possible to use anonymous function as script function input?

9 ビュー (過去 30 日間)
Kokalz
Kokalz 2012 年 10 月 15 日
Hey everyone!
I was wondering if there is any method to allow anonymous function to be used as an input. For example:
I have the following script:
function output = exampleF(input)
output = 3*input
And then use sin(x) as an input:
exampleF(sin(x))
By doing it like that I would get that x is not a defined variable.
Is there any way to program 'sin(x)' as an anonymous function ? in a same manner as
f = @(x) sin(x).
Thank you for your time!

採用された回答

Matt Fig
Matt Fig 2012 年 10 月 15 日
function output = exampleF(input)
output = @(x) 3*input(x);
Now from the command line:
T = exampleF(@(x) sin(x));
T(pi/2)
  4 件のコメント
Matt Fig
Matt Fig 2012 年 10 月 15 日
Kokalz, when MATLAB sees:
sin(x)
if first looks to see if sin is a local variable in order to index it with variable x. If not, then it looks to see if sin is a function and tries to pass it the argument x. Since you have not defined x, you get the error.
Now look at how MATLAB itself deals with the problem. When you call FZERO, you pass a function handle. When you call FSOLVE, LSQNONLIN, LSQCURVEFIT, ODE45, or most any other solving function in MATLAB, you pass in a function handle. So why do you want to code so differently than users of MATLAB are used to doing??
Matt Fig
Matt Fig 2012 年 10 月 15 日
Having said that, you can use the older, less recommended method of using strings:
function output = exampleF(input)
output = inline(['3*',input]);
Now from the command line:
T = exampleF('sin(x)');
T(pi/2)

サインインしてコメントする。

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2012 年 10 月 15 日
exampleF(@(x) sin(x))
However, you will find that multiplying a function handle by a constant is not allowed.
Is your desired output a numeric value or a new function handle ?
  2 件のコメント
Kokalz
Kokalz 2012 年 10 月 15 日
I am trying to write a function that would solve equations by using Newton-Raphson method. So I was wondering if it is possible to allow user input the function simply as 'sin(x)' and then do all the newton-raphson method steps with that function.
Walter Roberson
Walter Roberson 2012 年 10 月 15 日
Yes if you include the apostrophes, such as
exampleF('sin(x)')
Equivalent would be using command form,
exampleF sin(x)
but that would not be able to return a value to a variable.
It is not possible to write
exampleF(sin(x))
without having the sin(x) be evaluated before being passed in to exampleF

サインインしてコメントする。


per isakson
per isakson 2012 年 10 月 15 日
編集済み: per isakson 2012 年 10 月 15 日

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by