Use a function handle inside another function handle

11 ビュー (過去 30 日間)
Sudipta Ray
Sudipta Ray 2015 年 6 月 24 日
コメント済み: Sudipta Ray 2015 年 6 月 25 日
I need to find out the integral of some function Let's say f(x).*sin(x). I define a function handle y=@(x)f(x); Now I want to define another function handle z as z = @(x)y.*sin(x) so that I can integrate: int = integral(z,x1,x2). Matlab does not allow me to do this. Is there a way so I can define the function separately and then define the function handle for the integrand?

採用された回答

Steven Lord
Steven Lord 2015 年 6 月 24 日
You're missing one small piece in your definition of z. You can't multiply a function handle and a numeric value, but you can multiply the numeric value obtained by evaluating that function handle and a numeric value.
f = @cos;
y = @(x) f(x);
z = @(x) y(x).*sin(x); % Note y(x) instead of y
To test, compare evaluating the function using the function handle and evaluating the function normally, by calling COS and SIN:
v = 0:0.1:2*pi;
usingFH = z(v);
usingFun = cos(v).*sin(v);
isequal(usingFH, usingFun)
That last statement will return true.
  1 件のコメント
Sudipta Ray
Sudipta Ray 2015 年 6 月 25 日
Thank you Steven. It worked perfectly. I should have known, Matlab was giving me this error "operator '*' undefined for function handle". Now it is working fine. I needed this because I want to use different functions as an input.

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by