Is there a concise way of summing over multiple dimensions of an array?

조회 수: 26 (최근 30일)
Hello all,
Is there a concise way of summing over multiple dimensions, i.e. using just one sum function? I know if I have a defined array A, then I can do:
sum(A(:));
But what if I want to sum over a range of that array or some kind of calculated array? I would either have to use sum of sum of sum and so on to get the total sum or assign a variable to that temporary array? Thank you!

채택된 답변

Walter Roberson
Walter Roberson 2017년 12월 4일
Example:
V = @(M) M(:);
sum( V( SomeArray(1:18, 5:43, :, 2:9) ) )
  댓글 수: 1
Renat
Renat 2017년 12월 4일
Awesome! Thanks! Apparently, I can even specify sum(M(:)), which will make it even easier!

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

추가 답변 (2개)

Pooja Lalan
Pooja Lalan 2018년 11월 7일
편집: Pooja Lalan 2018년 11월 7일
Starting in R2018b, you can use this syntax
sum( SomeArray(1:18, 5:43, :, 2:9), 'all' )
sum( SomeArray(1:18, 5:43, :, 2:9), [1 2 3 4] )

Guillaume
Guillaume 2017년 12월 4일
Not sure it is concise, it avoids the multiple sum:
sum(reshape(A(yourange), 1, []))
  댓글 수: 1
Renat
Renat 2017년 12월 4일
I thought about that, but I erroneously thought I would need to use numel in there to specify the new shape. One more new thing I learned today about Matlab.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by