我是面向对象的编程的新手。这个问题似乎类似于以前问的问题,但我还没有找到解决方案的一个很大的区别:
我如何使用MATLAB中面向对象的编程设置新的变量,该变量的行为与矩阵(2D数组...)相似,但是为此,行/列将被编号{-2,-1,0,1 ...}(而不是{1,2,3 ...})?
我希望能够使用MATLAB在此新类中提供的所有常规向量操作。解决此变量中的值的方法是什么(例如,a [-1,2] = ...对于正常数组?我将如何执行简单A(MATLAB中向量的元素乘法)?和a(:,5)。* b(-1,:)'?
您可以为内置double
类子类子类,这将为您提供大部分功能。关于索引,您只需要编写自己的subsref
和subsasgn
方法。
由于您已分类为double
,因此所有正常矩阵操作(例如元素乘法,cumsum
等)将继续按预期工作。
这样的事情应该起作用。
classdef mymatrix < double
methods
function self = mymatrix(varargin)
% Constructor that simply calls the double constructor
self@double(varargin{:});
end
function res = subsref(self, subs)
% Call the usual subsref after modifying the subscripts
res = subsref@double(self, correctsubs(self, subs));
end
function res = subsasgn(self, subs, val)
% Call the usual subsasgn after modifying the subscripts
res = subsasgn@double(self, correctsubs(self, subs), val);
end
end
methods (Access = 'private')
function subs = correctsubs(self, subs)
% Function for converting subscripts
for k = 1:numel(subs)
% Only process () references and non-linear indices
if ~isequal(subs(k).type, '()')
continue
end
% Figure out the center of the matrix
mid = ceil(size(self) / 2);
% For each subscript, if it's numeric then add the middle
% shift amount to it to turn it into a normal subscript
for m = 1:numel(subs(k).subs)
if isnumeric(subs(k).subs{m})
subs(k).subs{m} = subs(k).subs{m} + mid(m);
end
end
end
end
end
end
然后,您可以像描述方式一样使用它。
m1 = mymatrix(magic(3));
m2 = mymatrix(magic(3));
% All normal matrix operations will work
m3 = m1 .* m2;
cumsum(m1, 1);
% You can also perform your special indexing
m4 = m1(:,-1);