how to put function as an input to another function?

I save a function call "nonliner" in matlab and I want to call this function as an input like
function [Ar,Br] = algopsols(nonliner,A,B); it give me an error
Is there any solution?
Thank you

回答 (1 件)

Star Strider
Star Strider 2016 年 1 月 30 日

0 投票

If you want to use it in the function, you do not have to pass it as an argument. Just include a call to it as part of the function code:
function [Ar,Br] = algopsols(A,B)
returned_values = nonliner( ... argument list ...);
. . . CODE . . .
end
If you want to pass it as an argument to your function, you have to pass it as a function handle (using an ‘@’ sign):
[Ar,Br] = algopsols(@nonliner,A,B)

4 件のコメント

Ahmed
Ahmed 2016 年 1 月 30 日
I used what you suggested,
[Ar,Br] = algopsols(@nonliner,A,B)
But, when I called the function "algopsols", I got an error
Star Strider
Star Strider 2016 年 1 月 30 日
What was the error?
Ahmed
Ahmed 2016 年 1 月 30 日
Error using algopsonls Too many input arguments.
Error in run_non_pso (line 15) [Ar,Br] = algopsonls(@nonliner,A,B)
Star Strider
Star Strider 2016 年 1 月 30 日
Well, if you want to pass the function as an input, you have to allow for it in the argument list:
function [Ar,Br] = algopsols(funname,A,B)
. . . CODE . . .
returned_values = funname( ... argument list ...);
. . . CODE . . .
end
then call it as:
[Ar,Br] = algopsols(@nonliner,A,B);
A simple illustration:
deriv = @(funname,x) (funname(x+1E-8) - funname(x))/1E-8; % Take A Simple Numerical Derivative
t = linspace(-pi, pi); % Time Vector
dsint_dt = deriv(@sin,t); % Derivative Of ‘sin(t)’
figure(1)
plot(t, sin(t), t, dsint_dt)
grid

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

カテゴリ

ヘルプ センター および File ExchangeStartup and Shutdown についてさらに検索

質問済み:

2016 年 1 月 30 日

コメント済み:

2016 年 1 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by