Multiple Outputs in object method?
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Guillaume
2015-6-30
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 个评论
Guillaume
2015-6-30
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Identification 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!