您可以为table
. 这有点棘手,因为 MATLAB 不允许您从table
该类继承,但通过重载subsref
andsubsasgn
运算符,您无论如何都可以获得大部分功能......
我在这个答案的底部包含了这个类,因为它有点长,用法如下所示:
>> foo(1) = MyVal(1); foo(2) = MyVal(2);
>> t = MyTable(foo') % Omitting the ";" calls our overloaded "disp" function
t =
Var1
____
1
2
您也可以使用它来提取数字数据(即foo
与其他数据一起使用的属性)t.numeric
,尽管我怀疑您需要将table2array
其用于与 一起使用uitable
,就像使用普通的table
.
classdef MyTable
properties ( Access = private )
table_
end
properties ( Dependent = true )
numeric
end
methods % Constructor and getter
function obj = MyTable( varargin )
% Store as a normal table internally
obj.table_ = table( varargin{:} );
end
function num = get.numeric( obj )
% By calling obj.numeric, output the table but with MyVal
% objects replaced by their "foo" property.
% This could be passed into a uitable, and is used in disp()
cls = varfun( @(x)isa(x,'MyVal'), obj.table_, 'OutputFormat', 'uniform' );
num = obj.table_;
for ii = find(cls)
num.(num.Properties.VariableNames{ii}) = [num.(num.Properties.VariableNames{ii}).foo].';
end
end
end
methods % Overloaded to emulate table behaviour
function disp( obj )
% Overload the disp function (also called when semi colon is
% omitted) to output the numeric version of the table
disp( obj.numeric );
end
% Overload subsref and subsasgn for table indexing
function varargout = subsref( obj, s )
[varargout{1:nargout}] = builtin( 'subsref', obj.table_, s );
end
function obj = subsasgn( obj, s, varargin )
obj.table_ = builtin( 'subsasgn', obj.table_, s, varargin{:} );
end
% Have to overload size and isa for workspace preview
function sz = size( obj, varargin )
sz = size( obj.table_, varargin{:} );
end
function b = isa( obj, varargin )
% This is only OK to do because we overloaded subsref/subsasgn
b = isa( obj.table_, varargin{:} );
end
end
end