Example of overloading times operator doesn't work
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I work out on one example in Matlab documentation showing application of subclasses of built-in types. In the example, DocUint8 class is derived from uin8 class and overrides its times operator. For some reasons, I couldn't get the overload function for this specific times operator work. As the below code points out, it is expected that the overloading operator should return an object of DocUint8 type, but instead I always get returned object of uint8 type. The strange thing is that my attempt to overload other operators such as "plus", "minus", "transpose", etc. all seem having no such problem (returned object is of subclass type). In addition, when setting breakpoint in the code, I don't see the debugging stops in the overloading method for this times operator. I did also try to clear all classes and clear all as well as restarting Matlab multiple times but none of those did work for me. Can someone explain to me if there's anything I have missed? Thanks!
classdef DocUint8 < uint8
methods
function obj = DocUint8(data)
if nargin == 0
data = uint8(0);
end
obj = obj@uint8(data); % Store data on superclass
end
function h = showImage(obj)
data = uint8(obj);
figure; colormap(gray(256))
h = imagesc(data,[0 255]);
axis image
brighten(.2)
end
function o = times(obj,val)
u8 = uint8(obj).*val;
o = DocUint8(u8);
end
end
end
This is what I get after multiplying the obj img1. I expect the returned obj should also be of type DocUint8.
>> img1 = DocUint8(rand(3)*255)
img1 =
3x3 DocUint8:
uint8 data:
150 120 50
53 59 58
77 215 44
>> img1*2
ans =
255 240 100
106 118 116
154 255 88
0 Kommentare
Antworten (1)
Steven Lord
am 14 Mai 2020
The * operator corresponds to the mtimes function. The operator for the times function is .* with the period in front.
img2a = img1*2 % uint8
img2b = img1.*2 % DocUint8
See the table at the end of this documentation page for a list of which functions correspond to which operators.
You should also modify your times method so that it doesn't assume the DocUint8 object is the first input. In the expression A.*B at least one of A and B must be an instance of the DocUint8 class, but it doesn't necessarily have to be A. Your code currently does not handle this case:
img3 = 2.*img1 % errors
0 Kommentare
Siehe auch
Kategorien
Mehr zu Subclass Applications finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!