MATLAB Answers

How to add more than two elements of a cell, where each element in the cell is a matrix of identicle size?

6 views (last 30 days)
Amit Kumar
Amit Kumar on 26 Feb 2019
Commented: Amit Kumar on 4 Mar 2019
Hi,
A cell contains N elements, where each element is a square matrix, M1, M2, ...., MN of identicle size (say2x2). To add all matrices i.e., M1+M2+...+MN, I tried to use
"plus(M{1,:})", but works well only when the cell contains only two matrices; else it showed following error
Error using +
Too many input arguments.
The sample Matlab code to add 4 matrices of size 2x2 is show below:
M1 = [1 2; 3 4]
M2 = [2 1; 4 3]
M3 = [2 3; 5 2]
M4 = [1 3; 3 5]
M = cell(1,4);
M{1,1} = M1
M{1,2} = M2
M{1,3} = M3
M{1,4} = M4
S = plus(M{1,:})
The error upon the execution is as follows:
Error using +
Too many input arguments.
Error in celle_add_eg (line 13)
S = plus(M{1,:})
Can anyone kindly suggest the possible solution to this error?
Thanks in advance!!

Accepted Answer

Shane L
Shane L on 26 Feb 2019
Try this:
sum(cat(3, M{:}), 3)
This first concatenates all of the arrays in the cells of M into a three-dimensional numeric array, and then it sums the numeric array along the third dimension.
  3 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!