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

additioncell arraysmatrix

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 2×2 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!!

Best Answer

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.