Multiple Outputs in object method?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
David
el 30 de Jun. de 2015
Comentada: David
el 1 de Jul. de 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!
0 comentarios
Respuesta aceptada
Guillaume
el 30 de Jun. de 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 comentarios
Guillaume
el 30 de Jun. de 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
Más respuestas (0)
Ver también
Categorías
Más información sobre Data Type Identification en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!