フィルターのクリア

Sum of many inputs

12 ビュー (過去 30 日間)
Dimitris
Dimitris 2011 年 2 月 26 日
Hi guys,
I want to implement a function that I find the sum of as many input arguments I give.
For example in one case it can be (a+b). In another (a+b+c+d...) or (a+b+c).
I try to use varargin but don't know how.. Any suggestions?
thanx d.

採用された回答

Matt Fig
Matt Fig 2011 年 2 月 26 日
function S = sumthemall(varargin)
% Takes as many scalars as you want, returns the sum.
S = sum([varargin{:}]);
.
.
.
EDIT O.k., since Walter wants to generalize it, I will generalize it further ;).
function S = sumthemall(varargin)
% Takes as many numeric arrays as you want, returns the sum.
S = 0;
for ii = 1:nargin
S = S+sum(varargin{ii}(:));
end
.
.
.
Now from the command line:
sumthemall(1,2,3,[4,5,6,7,8,9],magic(3),round(rand(3,4,5,6)*8))
ans =
1532
.
.
.
.
EDIT2
Here is a better (maybe?) generalization.
function S = sumthemall(varargin)
% Takes as many numeric arrays as you can dish and performs a sum.
% If all inputs are the same size (except for possible scalars), then the
% output will be that same size. If not, the result is a scalar sum of all
% elements of all arguments.
S = 0;
Sz = cellfun(@size,varargin,'Un',0);
sclrs = cellfun(@(x) isequal(x,[1 1]),Sz);
Nscl = Sz(~sclrs);
if all(cellfun(@(x) isequal(x,Nscl{1}),Nscl))
for ii = 1:nargin
S = S + varargin{ii};
end
else
for ii = 1:nargin
S = S + sum(varargin{ii}(:));
end
end
.
.
Now from the command line:
>> sumthemall(1,2,3,7,magic(3),round(rand(3)*80))
ans =
38 87 76
79 63 42
27 24 88
>> sumthemall(1,2,3,7,magic(3),round(rand(3)*80),[5 6])
ans =
430
  2 件のコメント
Walter Roberson
Walter Roberson 2011 年 2 月 26 日
You can do better than that, Matt :)
function S = sumthemall(varargin)
S = cellfun(@(x) x(:), varargin, 'Uniform', 0);
S = sum(vertcat(S{:}));
end
Matt Fig
Matt Fig 2011 年 2 月 26 日
Funny, too many CELLFUN calls already!

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2011 年 2 月 26 日
function S = sumthemall(varargin)
% Takes as many scalars, equal-length vectors, or
% equal-size arrays as you want, returns the sum.
if ~nargin
S = 0;
else
d = 1 + ndims(varargin{1});
S = sum( cat(d, varargin{:}), d );
end
end

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by