How to add matrices in a function with varying input arguments

4 views (last 30 days)
I have a function: myfunction(varargin), where the varargin are matrices. I want this function to add all of the matrices I input. Hows the best way of doing this?

Accepted Answer

James Tursa
James Tursa on 16 Jul 2014
Do you mean simply adding up all of the varargin individual inputs, like this?
if( nargin )
matrix_sum = varargin{1};
for k=2:nargin
matrix_sum = matrix_sum + varargin{k};
end
end

More Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 16 Jul 2014
You can use one cell array containing all your matrices
  3 Comments
Hail
Hail on 16 Jul 2014
Sorry I dont think I was clear. I want to create a function that no matter how many matrices I input, it will add them together. All of the matrices will have the same dimensions.
So if I had: M1=[1 2 3; 4 5 6] M2=[2 3 4; 5 6 7]
myfunction(M1,M2)
it'll out put
[3 5 7;9 11 13]

Sign in to comment.

Categories

Find more on Argument Definitions in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by