Sum over part of array without knowing array size

조회 수: 6 (최근 30일)
JE
JE 2015년 9월 9일
댓글: John D'Errico 2015년 9월 9일
I currently have a function that takes a two dimensional (2D) array as one of its inputs. Part of the function code sums over all but the first column of this input array, i.e.:
function DoSomething( Array2D, OtherInputs)
...
SumOverColumns = sum(Array2D(:, 2:end), 2);
...
end
I want to expand the use of the function so that the array can be 3D or more. However, I still want to be able so sum over all columns except the first one. I can't think of a general way to do this because I think that I need to specify ":" for every other dimension.
Any help would be much appreciated.
  댓글 수: 2
Cedric
Cedric 2015년 9월 9일
편집: Cedric 2015년 9월 9일
You need to define a little more precisely what happens with higher dimensions, and what it is that you want to output. In 2D you are summing over the 2nd dimension excluding the first column and outputting a column vector of sums. What happens in 3D? Do you still need to sum over the 2nd dimension only excluding the first column of each page (and hence output a 2D array of sums), or do you need to sum over dimensions 2 and 3 excluding the first, simultaneously (output a vector) or separately (output two 2D arrays)?
JE
JE 2015년 9월 9일
Hi Cedric
In the following, I've used a1 to denote the size of dimension 1 (of the input array), a2 for the size of the 2nd dimension and so on.
Yes, in the 2D example, the result is a column vector (e.g., a1 x 1).
For 3D, I want the output to be a1 x 1 x a3. For 4D, I want the output to be a1 x 1 x a3 x a4. and so on.

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

채택된 답변

John D'Errico
John D'Errico 2015년 9월 9일
편집: John D'Errico 2015년 9월 9일
Or more? How many more dimensions? Really high dimensional arrays will be huge, so it makes little sense to have a 300 dimensional array. Even a 2- dimensional array actually has infinitely many trailing singleton dimensions. So a 5x6 array is actually implicitly of size
[5,6,1,1,1,1,1,1,1,1, ...]
Suppose you are willing to assume your array will have no more than 5 dimensions in the future. Then the trivial solution is:
SumOverColumns = sum(Array2D(:, 2:end, :, :, :), 2);
There are ways to do this with more potential dimensions, but why bother?
  댓글 수: 4
JE
JE 2015년 9월 9일
Hi John
That works with one slight change to the 2nd line:
S = size(ArrayNd);
S(2) = 1;
SumOverColumns = reshape(sum(ArrayNd(:, 2:end,:), 2),S);
Thanks very much!
John D'Errico
John D'Errico 2015년 9월 9일
Oops, yes. You were summing on that dimension. Yes.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by