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!