How to sum up multiple matrices, element by element

조회 수: 20 (최근 30일)
Kuba
Kuba 2017년 11월 10일
댓글: Jan 2022년 3월 15일
So I've got multiple 100x100 matrices saved as a multidimensional Array a. Now I want to sum them up, element by element so the result is one 100x100 matrix. Since I got n matrices, I want to have a loop or similar, so I don't have to call every matrix by name like A1 + A2 + A3 + A4 ... = A. Example:
A =
1 1 1
2 2 2
3 3 3
B =
4 4 4
5 5 5
6 6 6
C =
7 7 7
8 8 8
9 9 9
D = [Some magical loop]
D =
12 12 12
15 15 15
18 18 18
  댓글 수: 1
Stephen23
Stephen23 2017년 11월 10일
편집: Stephen23 2017년 11월 10일
Your question contradicts itself: do you either have "as a multidimensional Array a" or do you have lots of separate matrices named "A1 + A2 + A3 + A4 ... " ?
If you have one ND array then you do not need lots of separate arrays. If you have lots of separate arrays then you really need one ND array!

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2017년 11월 11일
편집: Jan 2017년 11월 11일
If you really have a list of variables A1, A2, A3: This is a bad idea and impedes using the data. Prefer a multi-dimensional array A(m, n, k). Then the sum is trivial:
A = cat(3, ...
[1 1 1; ...
2 2 2; ...
3 3 3], ...
[4 4 4; ...
5 5 5; ...
6 6 6], ...
[7 7 7; ...
8 8 8; ...
9 9 9]);
D = sum(A, 3);
  댓글 수: 8
Stephanie Watermann
Stephanie Watermann 2022년 3월 15일
Thank you so much!
Jan
Jan 2022년 3월 15일
You are welcome.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Birdman
Birdman 2017년 11월 10일
편집: Birdman 2017년 11월 10일
A(:,:,1)=randi([1 3],100,100);
A(:,:,2)=randi([1 3],100,100);
A(:,:,3)=randi([1 3],100,100);
A(:,:,4)=randi([1 3],100,100);
B=zeros(size(A,1),size(A,2));
for i=1:size(A,3)
B=B+A(1:size(A,1),1:size(A,2),i);
end
disp(B)
  댓글 수: 2
Kuba
Kuba 2017년 11월 10일
Thanks a lot, it works perfectly!!
Jan
Jan 2017년 11월 11일
Note that
B = B + A(1:size(A,1),1:size(A,2),i);
can be processed much more efficient when written as:
B = B + A(:, :, i);
But the complete code can be simplified to:
A = randi([1 3], 100, 100, 4);
B = sum(A, 3);

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by