When subclassing "double" with new properties, is there an easy way to access the data value?
5 views (last 30 days)
Show older comments
Say I have a class subclassing double, and I want to add a string (Similar to the 'extendDouble' in the documentation). Is there an easy way to access the actual numeric value without the extra properties, particular for reassigning? Or if I want to change the value, will I have to recreate the value as a new member of the class with the new value and the same string?
e.g.
classdef myDouble < double
properties
string
end
methods
function obj = myDouble(s)
% Construct object (simplified)
obj.string = s;
end
end
end
----------
x = myDouble(2,'string')
x =
2 string
x = 3
x =
3 string
0 Comments
Accepted Answer
Jeffrey Clark
on 13 Jul 2022
Edited: Jeffrey Clark
on 13 Jul 2022
Sorry but the subsasgn and subsref will be needed (and maybe numArgumentsFromSubscript) just follow the example given, or use Customize Object Indexing - MATLAB & Simulink (mathworks.com) for MATLAB 2021b+ preferred pattern (but it isn't any easier or closer to what you really want).
It would be easier to not subclass a basic type, just have two properties for the string and numeric. Then when referencing the obj.property you get all the appropriate property functions like sqrt(x.val) and disp(['string is ' x.str]), but x = 3 would have to be done as x.val = 3
0 Comments
More Answers (1)
Aaron Kaw
on 6 Nov 2023
Edited: Aaron Kaw
on 6 Nov 2023
Try
x = myDouble(2,'string')
double(x)
I like to also add the following non-static method to my double subclasses:
function value = double(instance)
value = builtin('double', instance);
end
so that I can do
y = myDouble(2, 'string').double
if I only cared about the double value the class outputed for the particular usage of myDouble.
0 Comments
See Also
Categories
Find more on Construct and Work with Object Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!