フィルターのクリア

Is it possible to tell if another set method call is coming up?

8 ビュー (過去 30 日間)
Christian Veenstra
Christian Veenstra 2017 年 12 月 5 日
コメント済み: Greg 2017 年 12 月 5 日
I have an object that does a somewhat long calculation, stores the result, and then lets the user use it. If they change certain properties then it needs to be recalculated. So, in the set method for those properties, I just call the precalculation method. Ideally, if the user changed multiple properties at the same time - for example, set(obj,'A',a,'B',b) - then it wouldn't do the calculation twice. Is it possible for me to check how the set method was called? Ideally I could write something like:
classdef foo < matlab.mixin.SetGet
properties (SetAccess=private)
Expensive=[];
end
properties
a=1;
b=2;
end
methods
function DoSomethingHard(obj)
Expensive=SomeLongCalculation(obj.a,obj.b);
end
function set.a(obj,value)
obj.a=value;
if NoMoreSetCallsComingUp
obj.DoSomethingHard;
end
end
function set.b(obj,value)
obj.b=value;
if NoMoreSetCallsComingUp
obj.DoSomethingHard;
end
end
end
end
Except I don't know what "NoMoreSetCallsComingUp" would look like. Is this possible? Currently I'm just doing a lot of unnecessary computations...
  1 件のコメント
Greg
Greg 2017 年 12 月 5 日
If my recommended answer doesn't work, you might be able to do evalin('caller','nargin') to determine if multiple set commands were issued.
This is a VERY bad idea, for various reasons. Use at your own risk.

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

採用された回答

Greg
Greg 2017 年 12 月 5 日
I can't test it on this machine to confirm, but you should be able to define set for your class (as opposed to set.a and set.b individually). Then, parse the parameter-value pairs and call doSomethingHard at the end.
methods
function DoSomethingHard(obj)
Expensive=SomeLongCalculation(obj.a,obj.b);
end
function set(obj,varargin)
% Obviously want better input checking...
for iarg = 1:2:length(varargin)
obj.(varargin{iarg}) = varargin{iarg+1};
end
% Best practice is to call methods method(obj) vs. obj.method
% avoids confusion between methods and properties
DoSomethingHard(obj);
end
end

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by