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

26 visualizaciones (últimos 30 días)
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!

Respuesta aceptada

Walter Roberson
Walter Roberson el 4 de Dic. de 2017
Example:
V = @(M) M(:);
sum( V( SomeArray(1:18, 5:43, :, 2:9) ) )
  1 comentario
Renat
Renat el 4 de Dic. de 2017
Awesome! Thanks! Apparently, I can even specify sum(M(:)), which will make it even easier!

Iniciar sesión para comentar.

Más respuestas (2)

Pooja Lalan
Pooja Lalan el 7 de Nov. de 2018
Editada: Pooja Lalan el 7 de Nov. de 2018
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 el 4 de Dic. de 2017
Not sure it is concise, it avoids the multiple sum:
sum(reshape(A(yourange), 1, []))
  1 comentario
Renat
Renat el 4 de Dic. de 2017
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.

Iniciar sesión para comentar.

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by