假设有一个继承数组x
的类,添加了一些参数p
classdef test
properties
x
p
end
methods
function t=calculate(t)
[t.x,t.p]=calc(x,p);
end
function t=plus(t1,t2)
t.x=t1.x+t2.x;
end
end
end
众所周知,如何重载二进制运算符,如plus
、mtimes
、minus
等。如何为启用重载任何二进制矢量化运算符,或最终启用任何一元运算符,如mean
、abs
、max
等,以便直接应用于向量x
?例如,如何使S = mean(S);
与S.x = mean(S.x);
等效
发布于 2017-10-24 21:42:15
如果我正确理解您的问题,听起来您希望您的新类test
只继承为属性x
类定义的所有二进制和一元方法(并在调用它们时对属性x
进行操作),这样您就不必自己重新定义它们。
如果这是您想要的,那么我认为做类似事情的唯一可行方法是实际使用继承并使类test
成为属性x
类的子类。考虑到x
只是一个double
的简单情况,可以找到一个对内置double
类型进行子类分类的好示例这里。将该示例调整为您的示例,下面是实现类test
的一种方法
classdef test < double
properties
p
end
methods
function obj = test(x, p)
if (nargin < 2)
p = 0;
if (nargin < 1)
x = 0;
end
end
obj@double(x);
obj.p = p;
end
function sref = subsref(obj, s)
switch s(1).type
case '.'
switch s(1).subs
case 'p'
sref = obj.p;
case 'x'
x = double(obj);
if (length(s) < 2)
sref = x;
elseif (length(s) > 1) && strcmp(s(2).type, '()')
sref = subsref(x, s(2:end));
end
otherwise
error('Not a supported indexing expression')
end
case '()'
x = double(obj);
newx = subsref(x, s(1:end));
sref = test(newx, obj.p);
case '{}'
error('Not a supported indexing expression')
end
end
function obj = subsasgn(obj, s, b)
switch s(1).type
case '.'
switch s(1).subs
case 'p'
obj.p = b;
case 'x'
if (length(s) < 2)
obj = test(b, obj.p);
elseif (length(s) > 1) && strcmp(s(2).type, '()')
x = double(obj);
newx = subsasgn(x, s(2:end), b);
obj = test(newx, obj.p);
end
otherwise
error('Not a supported indexing expression')
end
case '()'
x = double(obj);
newx = subsasgn(x, s(1), b);
obj = test(newx, obj.p);
case '{}'
error('Not a supported indexing expression')
end
end
function disp(obj)
fprintf('p:');
disp(obj.p);
fprintf('x:');
disp(double(obj));
end
end
end
请注意:在类test
的对象上使用test
运算符和方法所得到的结果将返回double
类的结果,而不是您想要的test
。要获得您想要的行为,每次都必须将结果重新分配到属性x
,如下所示:
>> a = test(1:3, pi) % Create an object with p = pi, and x = [1 2 3]
a =
p: 3.141592653589793
x: 1 2 3
>> a.x = -a % Unary operation on a, and reassignment to x
a =
p: 3.141592653589793
x: -1 -2 -3
>> a.x = a+4 % Binary operation and reassignment
a =
p: 3.141592653589793
x: 3 2 1
>> a.x = mean(a) % Another unary operation and reassignment
a =
p: 3.141592653589793
x: 2
https://stackoverflow.com/questions/46625426
复制相似问题