Multiple Outputs in object method?

3 vues (au cours des 30 derniers jours)
David
David le 30 Juin 2015
Commenté : David le 1 Juil 2015
I'm working with OOP in matlab and I want to define a function to output multiple arguments. The idea is to easily concatenate the output or put in a cell array depending on my usage.
function varargout = getPoints(self)
if numel(self) > 1
for i = 1:numel(self)
varargout{i} = self(i).getPoints;
end
else
%Computation to get the points, results is always a 2x2 matrix
end
end
The idea now is now in other objects I can easily manipulate the results like
a = cat(3, allObjects.getPoints);
or like this
b = {allObjects.getPoints};
But I always just get one output out, only the first entry. How can I achieve the desired effect? Thanks in advance!

Réponse acceptée

Guillaume
Guillaume le 30 Juin 2015
The problem is that when you do
cat(3, allObjects.getPoints)
%or
{allObjects.getPoints}
you're only asking for one output. So, only the first cell of varargout is going to be used.
You could work around this, by assigning the output of your getPoints function to a cell array of the right size, like so:
c = cell(1, numel(allObjects));
[c{:}] = allObjects.GetPoints;
cat(3, c{:})
The other option is to change GetPoints to always have a single output:
function points = GetPoints(self)
%points is a cell array if self is an array, a matrix otherwise
if numel(self)
points = arrayfun(@(s) s.GetPoints, self, 'UniformOutput', false);
%or use your loop
else
%computation
end
end
In which case, the code on the receiving side is simply:
points = allObjects.GetPoints;
cat(3, points{:})
  3 commentaires
Guillaume
Guillaume le 30 Juin 2015
Not as a far as I know.
Another option is to use a property instead of a method. Then you could do:
cat(3, allObject.Points)
You could even make that Points property a dependent property, so that the points are calculated on the fly as you do in your GetPoints method:
classdef SomePointClass
properties (dependent)
Points;
end
methods
function points = get.Points(self)
%self is always scalar. If property is requested for an array
%matlab passes the array elements one by one to this function
%so always do points computation here as in the else clause
%of your GetPoints
points = randi(100, 5, 4); %e.g.
end
end
end
David
David le 1 Juil 2015
Yes I know that, but that means I cannot pass additional options and overloading in child classes gets cumbersome. Thanks for the help!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Identification dans Help Center et File Exchange

Produits

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by