Sum of a portion of 3D matrix elements

2 Ansichten (letzte 30 Tage)
Dmitrii Lukashevich
Dmitrii Lukashevich am 8 Apr. 2021
Hello,
I would like to find a sum of 3D matrix elements located in a one tetrahedron. For a matrix A with indices (i, j, k) I need to find a sum of elements with indices (i, j > i, k > j), i.e.
total = 0;
for i = 1:N
for j = i:N
for k = j:N
total = total + A(i,j,k);
Is there a way to do it in a vector/matrix manner without loops?
"Tril/triu" function doesn't work with 3D matricies.
Thanks in advance!

Akzeptierte Antwort

Matt J
Matt J am 8 Apr. 2021
Bearbeitet: Matt J am 8 Apr. 2021
[I,J,K]=ndgrid(1:N);
total = sum(A(I<=J & J<=K))
  2 Kommentare
Matt J
Matt J am 8 Apr. 2021
You can conserve some memory by using ndgridVecs instead ( Download )
[I,J,K]=ndgridVecs(1:N);
total = sum(A(I<=J & J<=K))
Dmitrii Lukashevich
Dmitrii Lukashevich am 8 Apr. 2021
Thank you a lot

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by