Use variable number of output when assigning varargout

I am creating a generic undercut for my class A that has an attrA attribute which is an instance of the class. While it works, it allows me to do things like

x = objA.attr1.methB(), 

      

which is what I tried to do in the first place.

function this = Class1(varargin)
    this.attrA = ClassB()
    this = class(this,'ClassA')

function this = ClassB()
    this.AttrB1 = 'valueB1'
    this.AttrB2 = 'valueB2'

function out = methB
    out = this.AttrB2

      

The problem I stumbled upon is this: when a method call is done in my subsref, I do it like this (detecting that this method, etc., is executed before):

methName = index(1).subs;                    
args = index(2).subs;
if iscell(args)                    
    varargout = {feval(methName,this,args{:})};            
else
    varargout = {feval(methName,this,args)};
end %end if iscell

      

The problem is that when the methName method supports a variable number of outputs, this varargout is not equivalent to [x, y, ...] (the number of outputs must be assigned in the call to subsref, so metName always returns one output, which is not always the same what I want (almost, but not always).

How can I tell methName how many cells you want? (I don't want to pass N as a parameter).

I am thinking something like creating a string str='[out1,out2,out3...]'

and then doing something like

eval([ 
str ...
'= {feval(methName,this,args{:})};'...
])

      

But I keep thinking there must be a more elegant way to do this.

+3


source to share


2 answers


If the number of outputs expected depends on the output arguments requested by your subfix, you can simply use nargout

like this:



[varargout{1:nargout}] = feval(methName,this,args{:});

      

+3


source


This solution worked, but I needed to add a little something for the individual outputs:

if iscell(args)
    [argout{:}] = feval(methName,this,args{:});            
else
    [argout{:}]= {feval(methName,this,args)};
end %end if iscell`
if isSingleCell(argout) && iscell(argout{1})`
    v = argout{1};
    argout{1}=v{1};
end

      



I'm not sure, but it might be that the last bit was only needed to fix something else (I had to fix a lot of other things to make this work). I'll come back to it when I finish what I tried to do with this class.

0


source







All Articles