question about function handles in OO
2 ビュー (過去 30 日間)
古いコメントを表示
Function handles are not behaving as I expect in an OO project, and I'd like to understand why not.
In brief, I have a class ("clOuter") which has an object of another class ("clInner") as one of its properties. I want to make a function handle to a function of the inner object (a handle that I will then pass elsewhere). But MATLAB doesn't recognize the function handle that I make in what seems to me the obvious way.
Here is a minimal example:
classdef clOuter < handle
properties
inner % outer class has an instance of inner class.
end
methods
function obj = clOuter % Constructor
obj.inner = clInner;
end
end
end
classdef clInner < handle
methods
function obj = clInner % Constructor
end
function result = Add(obj,x,y)
result = x + y;
end
end
end
% Demo script:
outer = clOuter; % Make the outer object. Its constructor makes the inner one.
fn = @outer.inner.Add; % Make a function handle to the inner object's function.
fn(3,2) % Call the function using its handle; this bombs.
% error message: Unrecognized function or variable 'outer.inner.Add'.
In short, why doesn't my function handle 'fn' work in this script? (MATLAB does say fn's class is 'function_handle'.) It's no problem to workaround the error, but I'd like to understand what it is about MATLAB's OO model that precludes making a function handle like this.
Thanks,
0 件のコメント
採用された回答
Bruno Luong
2024 年 9 月 21 日
編集済み: Bruno Luong
2024 年 9 月 21 日
Something extra must happen internally by the parse when you create function from method, but it only happens at the first level of reference.
I guess the parser somewhat confuses of the reference to the method itself and not calling it in the syntax with nested dotted: @outer.inner.Add
classdef clOuter < handle
properties
inner % outer class has an instance of inner class.
end
methods
function obj = clOuter % Constructor
obj.inner = clInner;
end
function result = Add(obj,x,y)
result = x + y;
end
end
end
classdef clInner < handle
methods
function obj = clInner % Constructor
end
function result = Add(obj,x,y)
result = x + y;
end
end
end
outer = clOuter; % Edit missing statement
fn = @outer.Add % It will automatically encapsulate in anonymous function @(varargin)outer.Add(varargin{:})
fn(4,2) % works
% However when you do this
fn = @outer.inner.Add % NO encapsilation occurs, don't ask me why
% But if you do manually
fn = @(varargin)outer.inner.Add(varargin{:})
fn(4,2) % will works
% You can also split the expression (knudge the parser)
inner = outer.inner;
fn = @inner.Add
fn(4,2) % works
We agree that MATMAB syntax is full of exeption as here, and not from few grammar rules.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Argument Definitions についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!