필터 지우기
필터 지우기

Multiple Outputs in object method?

조회 수: 6 (최근 30일)
David
David 2015년 6월 30일
댓글: David 2015년 7월 1일
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!

채택된 답변

Guillaume
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
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
David
David 2015년 7월 1일
Yes I know that, but that means I cannot pass additional options and overloading in child classes gets cumbersome. Thanks for the help!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by