calling method (and sum'ing answer) on every class instance in a matrix
    2 ビュー (過去 30 日間)
  
       古いコメントを表示
    
Hi, I asked a very similar question to this this morning for getting the sum of class properties in a matrix (cheers Daniel for the answer) but now I need to get the sum of method return values.
If I make a simple class;
MATLAB code
classdef ExampleClass < handle
 methods
   function obj = GetTotal(this)
      %In real life this is a calculation that returns a value.
      obj = 5;
   end
 end
end
And I make a collection of them;
MATLAB code
myCollection=[ExampleClass1; ExampleClass2; ExampleClass3; ExampleClass4];
Is there an easy way to get the sum of the GetTotal methods please? ie,
MATLAB code
sum([myCollection.GetTotal])
...would give 20?
Is it possible without making the method a dependent property?
Thanks for any help,
Tom.
0 件のコメント
採用された回答
その他の回答 (1 件)
  Daniel Shub
      
      
 2011 年 11 月 30 日
        Welcome to the joys of MATLAB OOP. While TMW will tell you that the array nature of the OOP system is a real plus, I find it a real pain to work with. Your options are to either limit your class to scalars (i.e., not allowing myCollection) or to write your own subsref. Something like:
function varargout = subsref(obj, S)
  for ii = 1:numel(obj)
    varargout{ii} = builtin('subsref', obj(ii), S);
  end
end
is a reasonable starting point, but it quickly gets more complicated.
0 件のコメント
参考
カテゴリ
				Help Center および File Exchange で Whos についてさらに検索
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


