MATLAB Answers

0

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

Asked by Amit Kumar on 26 Feb 2019
Latest activity Commented on by 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!!

  0 Comments

Sign in to comment.

1 Answer

Answer by Shane L
on 26 Feb 2019
 Accepted 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.

  3 Comments

Thanks for the reply, but it works only for scalar inputs in the matrix.
If I am trying to use this for symbolic variables, I am getting errror "Input arguments must be two-dimensional."
i tried the following as an example:
syms s
M1 = [s+1 2; 3 4]
M2 = [2 1; 4 3]
M3 = [2 3; 5 2]
M4 = [1 3; 3 5]
M = cell(1,3);
M{1,1} = M1
M{1,2} = M2
M{1,3} = M3
M{1,4} = M4
sum(cat(3, M{:}), 3)
On the execution, I am getting the following error:
Error using symengine
Input arguments must be two-dimensional.
Error in sym/privUnaryOp (line 943)
Csym = mupadmex(op,args{1}.s,varargin{:});
Error in sym/sum (line 54)
s = privUnaryOp(A, 'symobj::prodsumdim', num2str(dim), '_plus');
Error in celle_add_eg (line 16)
sum(cat(3, M{:}), 3)
Kindly, suggest the possible way out for this error.
Thanks.
Unfortunately, I don't have access to the symbolic toolbox, so I was unable to test this solution for symbolic variables. However, I think you have two options:
  1. The simplest option is likely to write a for-loop over the number of cells in M and add each matrix within the loop. This would be the most clear to a reader of the code, too. However, this may take some time if M is very large.
  2. If you want to be able to take the sum in one line, here is a way to do it with only 2-D matrices:
reshape(sum(reshape(cat(2,M{:}),[],length(M)),2),size(M{1}))
This concatenates the matrices together in the second dimension, reshapes them in a 2-D array that can be summed over the second dimension, and then reshapes the result back to your original array size. Caveat: I have not been able to test this for symbolic variables. Does this work for you?

Sign in to comment.