필터 지우기
필터 지우기

Automatic deep copy of handle inside class object.

조회 수: 6 (최근 30일)
SK
SK 2014년 9월 28일
편집: SK 2014년 9월 28일
Is there any way in Matlab to have automatic deep copy of a handle object that is contained inside a class? Occassionally, class methods return values that are a result of a long calculation. It may be inconvenient for the caller to store them and pass them around. It is more convenient to pass the class object instead. I don't want to write:
Obj = Obj.CalculateSomething(...)
which can be inconvenient. Also the function name does not suggest that it is a modifier. I would rather have the class silently cache the calculated values. So I want to have a cache object. For example:
classdef Cache < handle
properties
Data;
end
methods
function this = Cache(varargin)
assert(iscellstr(varargin), 'Cache: Inputs must be valid variable names. ');
numfields = numel(varargin);
vals = cell(numfields, 1);
this.Data = cell2struct(vals, varargin(:), 1);
end
function val = Get(this, fname)
val = this.Data.(fname);
end
function Set(this, fname, val)
this.Data.(fname) = val;
end
end
end
Then if I want to cache data inside a class, say DataCruncher, I would write:
classdef DataCruncher
properties (Access = 'private')
h_cache;
% ... other properties ...
end
methods:
function PreciousVals = BigWork(dcobj)
PreciousVals = dcobj.h_cache.Get('Vals')
if isempty(PreciousVals)
% ... Big work ...
dcobj.h_cache.Set('Vals', PreciousVals);
end
end
end
end
Of course the cache is shared by any copies of DataCruncher objects. However it works fine as long as a new Cache object handle is created in any class method that modifies DataCruncher in a way that affects the BigWork() calculation.
But sometimes things get complicated, so I want the h_cache to be deep copied automatically whenever DataCruncher is copied.
Is there any way at all to do this in Matlab? Can Matlab.mixin.Copyable help?
Thank you.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by