Multiple anonymous functions combined

2 ビュー (過去 30 日間)
Isktaine
Isktaine 2013 年 3 月 18 日
Hi,
I am trying ultimately to be able to define a new anonymous function from two previously defined functions, and pass this into a function. Say, for simplicity, I define:
D=@(d) d^2
C=@(c) c^c
then I try to define:
E=@(d,c) D(d)*C(c)
then this works. I can put in values of d and c and get (d^2)*(c^c) as an output from E. I am trying to understand how MATLAB defines the new function E. If I delete functions D and C from the workspace, and continue to call E(1,2) etc then E will continue to produce results, so it's as if MATLAB has stored C and D inside E itself.
However, if I pass E into a new function and ask it to calculate E(1,2) inside there - I get an error. (Undefined function or method 'mtimes' for input arguments of type 'function_handle'). So it's as if MATLAB has now forgotten D and C, so they are not built into E.
Can someone explain what is happening here? I'm just trying to grasp how these functions are working.
Thanks!
  1 件のコメント
Matt J
Matt J 2013 年 3 月 18 日
編集済み: Matt J 2013 年 3 月 18 日
However, if I pass E into a new function and ask it to calculate E(1,2) inside there - I get an error. (Undefined function or method 'mtimes' for input arguments of type 'function_handle').
This is not enough information. We need to know not just what error message you are seeing, but what particular statement in your code produces it. Please copy/paste the complete error message, ideally from a small example that we can run/reproduce it with.

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

回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 3 月 18 日
編集済み: Azzi Abdelmalek 2013 年 3 月 18 日
You should pass E through input argument of your function
Example
function y=yfcn(a,b,f)
y=f(a,b)+500
Then call your function
out=yfcn(2,3,E)
  2 件のコメント
Isktaine
Isktaine 2013 年 3 月 18 日
編集済み: Isktaine 2013 年 3 月 18 日
I have. So for example:
function out=Newfunction(E,c,d)
E(c,d)
end
But running
Newfunction(E,1,2)
yields the error: Undefined function or method 'mtimes' for input arguments of type 'function_handle'). So even though E has been passed in it doesn't appear to know what it is made up of.
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 3 月 18 日
編集済み: Azzi Abdelmalek 2013 年 3 月 18 日
For me it's working.Also it should be
function out=Newfunction(E,c,d)
out=E(c,d)
end

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


Sean de Wolski
Sean de Wolski 2013 年 3 月 18 日
You can use the function functions() to figure out the workspace of a E. Here is an example, as for the error - I cannot reproduce it:
function examplefh
D=@(d) d^2;
C=@(c) c^c;
E=@(d,c) D(d)*C(c);
passedInto(E)
ef = functions(E)
ef.workspace{1}
function passedInto(E)
E(1,2)

カテゴリ

Help Center および File ExchangeInteractive Control and Callbacks についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by