MATLAB Answers


cell Array of objects to object method

Asked by Francesco Piccioli on 14 Feb 2019
Latest activity Commented on by Walter Roberson
on 14 Feb 2019
Hi all, I'm new to OOP concepts and I'm trying to port an old code that used to make massive use of structs to a class-based architecture.
I have a class named "Component" with a method called "Cascade. This are the input parser lines of the Cascade method
function obj = Cascade(varargin)
switch nargin
case 1
if iscell(varargin{1})&&length(varargin{1})>1
nDev = length(varargin{1});
obj = Cascade(varargin{1},varargin{2});
for iD = 2:(nDev-1)
obj = Cascade(obj,varargin{iD+1});
error('one input argument is allowed for at least 1x2 cell arrays of devices');
case 2
if (varargin{1}.Out.nPorts==varargin{2}.In.nPorts)
Cmatrix = (1:varargin{1}.Out.nPorts)'*[1,1];
error('number of ports in cascaded devices do not correspond, provide a valid connection matrix');
case 3
Cmatrix = varargin{3};
case 4
error('Unsupported number of inputs');
CMP1 = varargin{1};
CMP2 = varargin{2};
I basically want to operate on two "components" and iteratively call the method if I pass a bigger collection.
Is there a way to make this method work if I call it like
CMP = Cascade({CMP1,CMP2,CMP3});
instead of throwing the error
Undefined function 'Cascade' for input arguments of type 'cell'?
Of course I could redefine "Cascade" as to be able to do something like
CMP = Cascade(CMP1, {CMP2,CMP3});
And this will obviously work, but it makes less logical sense to me. Another way would be of defining an external version of Cascade which just parse the inputs but I don't like this solution either since I want everything contained in the class definition.


Because Cascade can only operate on "Components". It doesn't make sense to have a general version of it.
Probably I should just accept that the right syntax is Cascade(o1,{o2...oN}) since I only Cascade one object with another object (which might be as well a cascade...). It just seemed more right to me the {o1..oN} flavour but it doesn't make much sense to how cell arrays are used within matlab. To reply to Adam and Walter no, I don't want to permit arrays of "Components".
Again, Since I'm new to OOP concepts the way I'm thinking about the architecture might very well be wrong, Thank you for your suggestions and comments!
on 14 Feb 2019
An array of objects would make the most sense, but if you don't want that then you have to just either a syntax that passes in 1 followed by a cell array of others (which seems very odd as a design) or create a static function where you handle your cell array. Since you are returning something called obj the static function approach seems next best.
Perhaps permit two different syntaxes: a cell array second parameter, or alternately a variable number of arguments each of which is a Component. Then
Cascade(01, {o2, ...oN})
Cascade(O1, o2, o3, ... oN)
would both work.

Sign in to comment.




0 Answers