Matlab - how to subclass dataset class supporting dataset parameter constructor

the dataset allows us to:

x = rand(10, 1); 
y = rand(10, 1);
d = dataset(x, y);

      

d will have 2 variables named "x" and "y", and the contents of x and y are the variable names from the workspace. The dataset () called call is equivalent to:

d = dataset({'x', x}, {'y', y});

      

when names are specified.

Now if I have a subclass of a dataset:

classdef mydataset < dataset
properties
end

methods
    function spec = mydataset(varargin)
        spec = spec@dataset(varargin{:});    
        % Add some more things to this subclass because that the reason I need a subclass
    end 
end 
end    

      

The problem is that if I call:

d = mydataset(x);

      

d will have a variable x, but the name will just be "var1". Workspace name 'x' is not recognized. If I don't call:

d = mydataset({'x', x});

      

I will not get the same effect.

Any solution?

Note that I don't want to lose out on other arguments parsing the capabilities of dataset (). It can handle really complex arguments, and I want to keep 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 a simple and common situation where mydataset () cannot pass things to dataatet () and get the same results. So this is an important situation. But to do this and lose other features of the dataset () is not worth it.

+3


source to share


1 answer


One option is to write the argument names yourself and build a cell, which you then pass to the dataset constructor, i.e. you create 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, now you've lost the ability to call mydataset

with the syntax {val, valname},...

, but it might be worth giving up. If you want to do this as well, you will need to write a conditional expression that will check the format of your input first, and build it args

differently depending on the format of the input.

Note, you cannot do the obvious thing and put your calls in the superclass constructor inside two branches of the if statement. In Matlab, superclass calls must be at the top level (i.e. you cannot put them inside loops or conditionals).

+1


source







All Articles