필터 지우기
필터 지우기

Handle class property inheriting value methods

조회 수: 3 (최근 30일)
Kevin S
Kevin S 2021년 11월 24일
답변: BhaTTa 2024년 6월 10일
Is there any way to create a handle class with the functionality of a value class, such that calling builtin methods of value classes would operate on a given Property? For example, let's say you have the class DataArray
classdef DataArray < handle
properties
Value
Unit
end
methods
function obj = DataArray(Value,Unit)
obj.Value = Value;
obj.Unit = Unit;
end
end
end
It would be very convenient to tell Matlab that any value methods (e.g. max, min, std...) should be applied to obj.Value without needing to explicitly define each method. Is there any way to accomplish this?

답변 (1개)

BhaTTa
BhaTTa 2024년 6월 10일
Hi @Kevin S , you can immplement the value methods using manual delegation
For a few methods, you could manually implement the delegation by defining methods in your DataArray class that call the built-in functions on the Value property. Here's an example for max, min, and std:
classdef DataArray < handle
properties
Value
Unit
end
methods
function obj = DataArray(Value, Unit)
obj.Value = Value;
obj.Unit = Unit;
end
% Delegating max
function result = max(obj)
result = max(obj.Value);
end
% Delegating min
function result = min(obj)
result = min(obj.Value);
end
% Delegating std
function result = std(obj)
result = std(obj.Value);
end
end
end
you can call max on an instance of DataArray, like so:
dataArray = DataArray([1, 2, 3; 4, 5, 6], 'units');
maxValue = max(dataArray);

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by