Default get method to return specific property

1 view (last 30 days)
I'm in the process of refactoring some MATLAB legacy software involving data obtained during a broad set of tests. I'm trying to create a class that contains the data of each individual channel, together with some extra info (e.g. its physical units).
Just for the sake of placing this question here, the class could look like this:
classdef Channel < handle
properties (Access = 'private')
prvValue, prvUnits;
end
properties (Dependent)
value, units;
end
methods
function this = Channel(value, units)
this.value = value;
this.units = units;
end
function set.value(this, value)
this.prvValue = value;
end
function out = get.value(this)
out = this.prvValue;
end
function set.units(this, units)
this.prvUnits = units;
end
function out = get.units(this)
out = this.prvUnits;
end
end
end
You can create an object of such a class with something like:
> ch1 = Channel([1:10], 'm');
And access to its dependent properties with:
>> ch1.value
ans =
1 2 3 4 5 6 7 8 9 10
>> ch1.units
ans =
'm'
This would nonetheless require to change every single line in the legacy code that access to the data from something like "ch1" to "ch1.value".
Now my question: is there any way to define a sort of "default get method" that returns a particular property of the class ("value", in this case)? In other words, something that behaves like this:
>> ch1
ans =
1 2 3 4 5 6 7 8 9 10
>> ch1.units
ans =
'm'
Any help will be welcome. Thanks a lot.

Answers (1)

Guillermo Benito
Guillermo Benito on 1 Apr 2020
I think I have found in the meantime something that seems -so far- to do exactly what I was aiming at: make the new class inherit from MATLAB's standard double class:
classdef ChannelDouble < double
properties
units
end
methods
function this = ChannelDouble(data, units)
this = this@double(data);
this.units = units;
end
end
end
This class delivers:
>> ch1 = ChannelDouble([1:10], 'm')
ch1 =
1×10 ChannelDouble array with properties:
units: 'm'
double data:
1 2 3 4 5 6 7 8 9 10
>> ch1.^2 % <--- Standard notation returns the data just like a double array would do
ans =
1 4 9 16 25 36 49 64 81 100
>> ch1.units
ans =
'm'
If anybody can think of a better solution your, please let me know. Otherwise I will leave this reply here in case it can help somebody with a similar problem.

Community Treasure Hunt

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

Start Hunting!