what is the function that let me add matrix?

1 view (last 30 days)
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.

Accepted Answer

Guillaume
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
Mohammad
Mohammad on 4 Jul 2015
Edited: Mohammad on 4 Jul 2015
Those are matrices A and B that need to be calculated as follows.
A(:,:,1)=a(:,:,1)+a(:,:,2)+......a(:,:,28)
A(:,:,2)=a(:,:,29)+a(:,:,302)+......a(:,:,56)
.
.
.
.
A(:,:,m1)=a(:,:,.........
and similarly for b
B(:,:,1)=b(:,:,1)+b(:,:,2)+......b(:,:,28)
B(:,:,2)=b(:,:,29)+b(:,:,302)+......b(:,:,56)
.
.
.
.
B(:,:,m1)=b(:,:,.........
so It seems I need to apply changes like this following
for k=1:m1
Ex(:,k) = A(:,:,k) * SAp(:,k) + B(:,3,k); % nD matrix multiply
end
TotNu=28*m1
Guillaume
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

Sign in to comment.

More Answers (0)

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!