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

1 Ansicht (letzte 30 Tage)
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!!

Akzeptierte Antwort

Shane L
Shane L am 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 Kommentare
Shane L
Shane L am 26 Feb. 2019
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?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by