Azzera filtri
Azzera filtri

When subclassing "double" with new properties, is there an easy way to access the data value?

2 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Jeffrey Clark
Jeffrey Clark il 13 Lug 2022
Modificato: Jeffrey Clark il 13 Lug 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

Più risposte (1)

Aaron Kaw
Aaron Kaw il 6 Nov 2023
Modificato: Aaron Kaw il 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.

Categorie

Scopri di più su Construct and Work with Object Arrays in Help Center e File Exchange

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by