what is the function that let me add matrix?
1 view (last 30 days)
Show older comments
I am looking for a function that can be utilized for adding several matrix, something like as what SIGMA from 1....n where the n is 1,2,3,...n. but here I want to add matrix.
Alternatively, I can do this with loop but I have been concerned about being time-consuming computationally. is there any effective and fast way to do this, please let me know.
0 Comments
Accepted Answer
Guillaume
on 3 Jul 2015
It all depends on how your matrices are stored.
The worst case, they're all stored as individual variables. A bad idea to start with. Transform them into one of the other two options.
Second option, is they're all stored in a cell array. The simplest thing would be to concatenate them all into a single matrix of a higher dimension and apply sum on that:
matrices = {rand(5,5,5); rand(5,5,5); rand(5,5,5)}; %store 3x 3D matrices
higherdim = ndims(matrices{1}) + 1;
matricessum = sum(cat(higherdim, matrices{:}), higherdim)
The last option it that they're already stored all together in a matrix of a higher dimension, in which case, just apply the sum function:
matrices = cat(4, rand(5,5,5), rand(5,5,5), rand(5,5,5)); %store 3x 3D matrices
matricessum = sum(matrices, 4);
4 Comments
Guillaume
on 6 Jul 2015
It would have been much simpler if you'd explained that in your question. You're trying to sum together some pages of the same matrix. Use reshape to put together all the pages you want to sum:
assert(mod(size(A, 3), 28) == 0); %otherwise it's not possible
A = sum(reshape(a, size(A, 1), size(A, 2), 28, []), 4)
%same for B
More Answers (0)
See Also
Categories
Find more on Data Type Identification 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!