Matlab - 如何创建数据集类的子类,保留数据集参数构造函数 [英] Matlab - how to create a subclass of dataset class keeping the dataset parameter constructor
问题描述
dataset allows us to do:
x = rand(10, 1);
y = rand(10, 1);
d = dataset(x, y);
d will have 2 variables with name 'x' and 'y' and content x and y - variable names are obtained from the workspace. The dataset() call above is equivalent to:
d = dataset({'x', x}, {'y', y});
when the names are specified.
Now if I have a subclass of dataset:
classdef mydataset < dataset
properties
end
methods
function spec = mydataset(varargin)
spec = spec@dataset(varargin{:});
% Add some more things to this subclass because that's the reason I need a subclass
end
end
end
The problem is, if I call:
d = mydataset(x);
d will have the variable x but the name is just 'var1'. The workspace name 'x' is not recognized. Unless I call:
d = mydataset({'x', x});
I will not get the same effect.
Any solution?
Note that I do not want to lose other argument parsing abilities of dataset(). It can process really complicated arguments, and I do want to preserve that.
http://www.mathworks.com/help/toolbox/stats/dataset.html
A = dataset(varspec,'ParamName',Value)
A = dataset('File',filename,'ParamName',Value)
A = dataset('XLSFile',filename,'ParamName',Value)
A = dataset('XPTFile',xptfilename,'ParamName',Value)
The example in this question with mydataset(x) is the a simple and commonly encountered situation that mydataset() can't pass things to dataset() and obtain the same results. Thus it's an important situation. But to do just that and lose other capabilities of dataset() is not worth it.
One option is to capture the argument names yourself and build a cell that you then pass in to the dataset constructor, i.e. you build a cell that looks like
{{Var1 VarName1}, {Var2 VarName2}, ...}
A quick and dirty solution:
classdef mydataset < dataset
properties
end
methods
function self = mydataset(varargin)
for k = 1:nargin
args{k} = {varargin{k}, inputname(k)};
end
self = self@dataset(args{:});
end
end
end
Now if I call it:
>> x=1;
>> y=2;
>> mydataset(x,y)
ans =
x y
1 2
Of course, you've now lost the ability to call mydataset
with the {val, valname},...
syntax, but maybe that's worth giving up. If you also wanted to be able to do that, you would need to write a conditional that checks the format of your input first, and builds args
differently depending on the input format.
Note that you can't do the obvious thing and put your calls to the superclass constructor inside two branches of an if statement. In Matlab, calls to the superclass have to be at the top level (i.e. you can't put them inside loops or conditionals).
这篇关于Matlab - 如何创建数据集类的子类,保留数据集参数构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!