필터 지우기
필터 지우기

The sum of stacked matrices

조회 수: 2 (최근 30일)
Shaun VanWeelden
Shaun VanWeelden 2012년 12월 22일
I have a 3-d matrix and I want to find the sum so that every element in the sum matrix is the sum of all the elements in that corresponding i,j location. I know that sounds confusing probably so for example:
>> A=zeros(3,3,3);
>> A(:,:,1)=[1 1 1; 1 0 1; 0 0 0];
>> A(:,:,2)=[1 1 1; 0 0 1; 0 1 0];
>> A(:,:,3)=[1 0 1; 0 1 0; 0 1 0];
Would give me a sum matrix that would be:
[ 3 2 3
1 1 2
0 2 0 ]
I realize I could reshape the matrices into a vector, sum them, and then reshape them back into the matrix, and that I could use for loops, but both of those seem over complicated and I would be doing this with a pretty large amount of data so speed is ideal :)
Thanks in advance!
-Shaun

채택된 답변

Roger Stafford
Roger Stafford 2012년 12월 22일
sum(A,3)
Roger Stafford
  댓글 수: 2
Shaun VanWeelden
Shaun VanWeelden 2012년 12월 22일
Well how bout that, that was sure easy haha
Question though, how does that 3 work? I was looking in the sum documentation and found that it sums along the second argument as the dimension, but I guess I don't understand what this means. Could you help explain it?
And by a similiar note, I tried finding the entire sum of a 2d matrix by doing sum(a2dMat,2) to see if it would give me just one value as the sum of all elements, but that did not work so now I'm a little confused as to how the second arg works in Sum
Roger Stafford
Roger Stafford 2012년 12월 22일
No, it sums along the third dimension, which is what you asked for. That is what the '3' refers to.
To get the entire sum of a two-dimensional array you need to either use two calls to 'sum' or convert the array to one-dimension and sum that:
sum(sum(A))
or
sum(A(:))
Roger Stafford

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by